当前位置: 首页 > 知识库问答 >
问题:

在Spring启动中使用 PostgreSQL 驱动程序创建数据源时出现异常

越勇锐
2023-03-14

我尝试使用Spring Boot创建一个非web应用程序,以MKyong的示例为例,但我得到了以下错误:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.5.RELEASE)

(...) Several not relevant INFO log lines

2018-12-12 11:45:29.420 ERROR 30866 --- [ main] com.zaxxer.hikari.HikariConfig           : Failed to load driver class org.postgresql.Driver from HikariConfig class classloader sun.misc.Launcher$AppClassLoader@18b4aac2
2018-12-12 11:45:29.423  WARN 30866 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'ldConfiguration': Could not bind properties to 'LdConfiguration' : prefix=datasources.ld, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'datasources.ld' to es.ortoplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64
2018-12-12 11:45:29.435  INFO 30866 --- [ main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-12-12 11:45:29.440 ERROR 30866 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'datasources.ld' to es.oplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64:

    Property: datasources.ld.driverclassname
    Value: org.postgresql.Driver
    Origin: class path resource [application.yml]:3:22
    Reason: Failed to load driver class org.postgresql.Driver in either of HikariConfig class loader or Thread context classloader

Action:

Update your application's configuration

我的conf文件(application.yml)是

datasources:
  ld:
    driverClassName: org.postgresql.Driver
    jdbc-url: jdbc:postgresql://localhost:5432/oplus
    username: user123
    password: 123456
    connection-test-query: SELECT 1

在我的专业pom中。我添加的xml文件:

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <!--<version> (managed by Spring Boot)42.2.5 </version> -->
</dependency>

我的切入点类:

@SpringBootApplication
public class App implements CommandLineRunner {

    @Autowired private UsuarioRepository usuarioRep;
    @Override
    public void run(String... args) throws Exception {
        App app = new App();
        System.out.printf("Users: %1d", app.usuarioRep.count());

    }

    public static void main(String[] args) throws ClassNotFoundException {
        //Class.forName("org.postgresql.Driver");
        SpringApplication.run(App.class, args);

    }

}

如您所见,我已尝试检查该类是否已在类路径中。如果我取消注释该行,我得到一个类不发现异常,所以看起来错误是由于 Maven 不包括依赖项引起的。我试图将作用域设置为运行时,但无论如何都失败了。

不管怎样,这是我的配置类:

@Configuration
@ConfigurationProperties(prefix = "datasources.ld")
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "postgreEntityManagerFactory", transactionManagerRef = "postgreTransactionManager",
        basePackages = "es.plus.l.dao")
public class LdConfiguration extends HikariConfig {

    @Bean(name = "postgreDataSource")
    @Primary
    public DataSource dataSource() {
        return new HikariDataSource(this);
    }

    @Bean(name = "postgreEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean postgreEntityManagerFactory(
            final EntityManagerFactoryBuilder builder,
            @Qualifier("postgreDataSource") final DataSource dataSource) {
        final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setJpaVendorAdapter(this.vendorAdaptor());
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPersistenceUnitName("postgre");
        entityManagerFactoryBean.setPackagesToScan("es.oplus.ld.model");
        entityManagerFactoryBean.setJpaProperties(this.jpaHibernateProperties());
        entityManagerFactoryBean.afterPropertiesSet();
        return entityManagerFactoryBean;
    }

    @Bean(name = "postgreTransactionManager")
    @Primary
    public PlatformTransactionManager postgreTransactionManager(
          @Qualifier("postgreEntityManagerFactory") final EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }

    private HibernateJpaVendorAdapter vendorAdaptor() {
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        // put all the adapter properties here, such as show sql
        return vendorAdapter;
    }

    private Properties jpaHibernateProperties() {
        final Properties properties = new Properties();
        // put all required jpa propeties here
        return properties;
    }

}

共有3个答案

袁弘方
2023-03-14

确保 pom 中同时具有 JDBC 驱动程序和后压缩 SQL 依赖项.xml如下所示:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency> 
越飞翮
2023-03-14

将下一段代码添加到pom.xml:

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
胡星汉
2023-03-14

我发现了问题:Eclipse正确显示了依赖项,但由于该类似乎并不真正存在,我尝试手动运行它,因此当我执行时:

mvn clean install

我从Maven那里得到了这个错误。

error reading /home/pablo/.m2/repository/org/postgresql/postgresql/42.2.5/postgresql-42.2.5.jar; invalid LOC header (bad signature)

因此,这个错误是由Maven下载了一个损坏的jar版本引起的。

删除它以强制重新下载解决了问题。

 类似资料:
  • 得到 错误[SpringApplication]应用程序启动失败org.springframework.beans.factory.BeanCreationException:创建名称为myEntityManagerFactory的bean错误定义在类路径资源[com/员工/服务/配置/DBConfiguration.class]:调用init方法失败;嵌套异常是java.lang.NullPoi

  • 我已经成功地使用Spring Boot 1.0.2开发了一个原型。发布(直到今天才发布1.0.1版本)。 我已经搜索并尝试了一些解决方案,比如:Spring Boot jdbc数据源自动配置在独立的tomcat Spring Boot/Spring数据导入上失败。sql不运行Spring-Boot-1.0.0。RC1 他们都建议让Spring Boot完成这项工作。使用H2时,一切正常,但当我尝试

  • 我在本地有一个引导corda网络,并将这些工件分发给相应的VM。当我启动其中一个节点时,我收到以下错误:我使用azure sql作为后端,并且使用corda Enterprise 4.3编译了jar,并且使用的数据库驱动程序是jdbc 6.4。 IntelliJ项目目标设置为仅Javajdk 1.8。 基本信息。-数据库连接url是< br> : jdbc:sqlserver://

  • 当我尝试运行spring boot应用程序时,我遇到了以下异常: 组织。springframework。豆。工厂BeanCreationException:创建名为“configurationPropertiesBeans”的bean时出错,该bean在类路径资源[org/springframework/cloud/autoconfigure/ConfigurationPropertiesRebi

  • 我正在尝试使用简单的spring启动应用程序。我在ApplicationContext上启动应用程序时遇到问题。 2017-04-26 11:17:31.101警告14528---[main]s.c.a.AnnotationConfigApplicationContext:上下文初始化期间遇到异常-取消刷新尝试:org。springframework。豆。工厂未满足的PendencyExcepti

  • 问题内容: 我正在尝试使用servlet上的Java驱动程序连接到mlab上托管的MongoDB数据库。 问题是我遇到以下错误: 我看了一个答案(如何解决ClassNotFoundException:com.mongodb.connection.BufferProvider?),该答案向我强调了我需要其他jar,自从我下载了这些jar之后,仍然出现此错误。 我正在使用Eclipse并将这三个jar