在 Spring Boot 中使用 PostgreSQL 驱动程序创建数据源时出现异常 [英] Exception when creating datasource with PostgreSQL driver in Spring Boot

查看:29
本文介绍了在 Spring Boot 中使用 PostgreSQL 驱动程序创建数据源时出现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照 MKyong 的例子,但我得到以下错误:

I'm trying to create a non-web application using Spring Boot following a MKyong's example, but I got the following error:

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

My conf file (application.yml) is

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

并在我的 Maven pom.xml 文件中添加:

And in my Maven pom.xml file I added:

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

    }

}

如您所见,我已尝试检查该类是否已在类路径中.如果我取消注释该行,我会收到 ClassNotFoundException,因此错误似乎是由于 Maven 不包含依赖项而引起的.我试图将范围设置为 runtime,但它还是失败了.

As you can see, I've tried to check if the class is already in the classpath. If I uncomment that line I got a ClassNotFoundException, so it seems the error is caused because Maven is not including the dependency. I've tried to set the scope as runtime, but it fails anyway.

无论如何,这是我的配置类:

Anyway, here is my Configuration 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;
    }

}

推荐答案

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

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:

mvn clean install

我从 Maven 得到这个错误

I got this error from 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版本引起的.

So the error was caused by Maven downloading a corrupt version of the jar.

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

Deleting it to force a new download fixed the issue.

这篇关于在 Spring Boot 中使用 PostgreSQL 驱动程序创建数据源时出现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆