使用Spring Boot创建PostgreSQL驱动程序时出现异常

37

我正在尝试使用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

我的配置文件(application.yml)是

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文件中添加了以下内容:

<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,但无论如何都会失败。

无论如何,这是我的Configuration类:

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

}

请参考以下链接:https://dev59.com/w6vka4cB1Zd3GeqPpC7y - user7294900
尝试重写您的application.yml文件以具有以下结构:spring:datasource:id:,然后是像jdbcUrl和driverClassName这样的属性..并且还尝试添加此依赖项:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> - vanillaSugar
@vanillaSugar 我使用了spring-boot-starter-jpa(它添加了jdbc依赖项),并尝试了驼峰式的方法,但是我仍然得到了相同的错误。 - Pablo Lozano
找到根本原因了,感谢您的评论。 - Pablo Lozano
嗨@PabloLozano,是什么导致了这个问题?我遇到了同样的错误。 - Ray
我写了一个答案,请看下面。 - Pablo Lozano
5个回答

23

我找到了问题所在: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文件,导致了这个错误。

删除它以强制重新下载就可以解决这个问题。


你可能想要找出为什么这个构件被损坏了。 - Thorbjørn Ravn Andersen
网络连接不稳定 :). - Witold Kaczurba
如果你正在使用Gradle,尝试执行以下命令:./gradlew clean build - undefined

20

将下面的代码添加到pom.xml文件中:

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

9

请确保在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> 

1
如果您正在使用IntelliJ Idea,则请重新启动您的IDE。

0
在我的情况下,pom.xml文件缺少以下依赖项。添加以下代码即可正常工作:
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

这是由Kirill和Tegveer编写的相同答案。 - Pablo Lozano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接