简体   繁体   English

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

[英]Exception when creating datasource with PostgreSQL driver in Spring Boot

I'm trying to create a non-web application using Spring Boot following a MKyong's example , but I got the following error:我正在尝试按照MKyong 的示例使用 Spring Boot 创建一个非 Web 应用程序,但出现以下错误:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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

My conf file (application.yml) is我的 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

And in my Maven pom.xml file I added:在我的 Maven pom.xml 文件中,我添加了:

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

My entry point class:我的入口点 class:

@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);

    }

}

As you can see, I've tried to check if the class is already in the classpath.如您所见,我已尝试检查 class 是否已在类路径中。 If I uncomment that line I got a ClassNotFoundException, so it seems the error is caused because Maven is not including the dependency.如果我取消注释该行,我会得到一个 ClassNotFoundException,所以错误似乎是因为 Maven 不包括依赖项。 I've tried to set the scope as runtime , but it fails anyway.我试图将 scope 设置为runtime ,但它还是失败了。

Anyway, here is my Configuration class:无论如何,这是我的配置 class:

@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;
    }

}

add next code to pom.xml:将下一个代码添加到 pom.xml:

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

I found the problem: Eclipse showed the dependencies properly, but as it seemed the class was not really present, I tried to run it manually, so when I executed: 我发现了问题:Eclipse正确地显示了依赖关系,但是因为它似乎并没有真正存在,所以我尝试手动运行它,所以当我执行时:

mvn clean install

I got this error from Maven 我从Maven得到了这个错误

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

So the error was caused by Maven downloading a corrupt version of the jar. 因此,错误是由Maven下载jar的损坏版本引起的。

Deleting it to force a new download fixed the issue. 删除它以强制新下载修复了该问题。

Make sure you have both JDBC driver and PostgreSQL dependencies in pom.xml as follows:确保在 pom.xml 中同时具有 JDBC 驱动程序和 PostgreSQL 依赖项,如下所示:

    <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> 

In my case the pom.xml was missing below dependency.在我的例子中,pom.xml 在依赖项下丢失了。 Add below code and should work fine:添加以下代码,应该可以正常工作:

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

if you are using IntelliJ Idea then restart your IDE如果您使用的是 IntelliJ Idea,则重新启动您的 IDE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过Spring xml数据源配置postgresql驱动程序 - Configuring postgresql driver through Spring xml datasource 测试时使用数据源进行Spring Boot - Spring Boot with datasource when testing 在 Spring Boot 中创建数据源时出错 - Error while creating datasource in spring boot Spring 引导 - PostgreSQL 驱动程序无法位于类路径中 - Spring Boot - PostgreSQL driver cannot be located in classpath 创建Spring Boot Otka资源服务器时出现异常 - Exception when creating Spring Boot Otka resource server 为什么我尝试在 Spring Boot 应用程序上配置数据库连接时会获得此异常? 创建名为“dataSource”的 bean 时出错 - Why am I obtaining this exception trying to configure DB connection on a Spring Boot application? Error creating bean with name 'dataSource' Spring Boot 1.4 @DataJpaTest - 创建名为“dataSource”的 bean 时出错 - Spring Boot 1.4 @DataJpaTest - Error creating bean with name 'dataSource' 创建名为&#39;dataSource&#39;+ Spring Boot + Hibernate的bean时出错 - Error creating bean with name 'dataSource' + Spring Boot + Hibernate Spring boot - 配置第二个数据源以及gloud gcp postgresql主数据源 - Spring boot - Configure second datasource along with gloud gcp postgresql primary datasource Spring Boot Multiple Datasource - Spring Boot Multiple Datasource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM