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



我试图按照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

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

在我的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
@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正确地显示了依赖项,但由于该类似乎并不真正存在,我尝试手动运行它,所以当我执行:

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版本引起的。

删除它以强制进行新的下载解决了这个问题。

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

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

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

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

在我的案例中,pom.xml在依赖项下面缺失。添加以下代码,应该可以正常工作:

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

最新更新