我刚刚创建了一个新的 SpringBoot 应用程序 (Java11),并且正在尝试连接到 Postgres 数据库。
当我启动 SpringBoot 应用程序时,尝试连接数据库时出现错误。错误报告它Cannot load driver class: org.postgresql.Driver
。
问题
如何更改我下面的配置以使 SpringBoot 应用程序连接到数据库?
数据库版本
<块引用>PostgreSQL 12.6 on x86_64-apple-darwin16.7.0,由 Apple LLVM 编译 版本 8.1.0 (clang-802.0.42),64 位
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
application.properties
# pims datasource
spring.datasource.url=jdbc:postgresql://localhost:5432/pims
spring.datasource.username=postgres
spring.datasource.password=
spring.datasource.driverClassName=org.postgresql.Driver
#spring.datasource.driver-class-name=org.postgresql.Driver
#spring.jpa.database-platform=postgres
spring.jpa.show-sql=true
spring.datasource.dbcp2.test-while-idle=true
spring.datasource.dbcp2.validation-query=select 1
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
当我运行 @SpringBootApplication
类时,SpringBoot 开始按预期启动,但出现以下错误。
错误
<块引用>启动 ApplicationContext 时出错。显示条件报告
在启用“调试”的情况下重新运行您的应用程序。 2021-06-15 11:58:51.770
错误 68967 --- [主要] o.s.boot.SpringApplication
: 应用程序运行失败
org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“dataSourceScriptDatabaseInitializer”的 bean 时出错 在类路径资源中定义 [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: 通过方法表达的不满足的依赖 'dataSourceScriptDatabaseInitializer' 参数 0;嵌套异常是 org.springframework.beans.factory.BeanCreationException:错误 使用在类路径资源中定义的名称“dataSource”创建 bean [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: 通过工厂方法的 Bean 实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException: 失败 实例化 [com.zaxxer.hikari.HikariDataSource]:工厂方法 'dataSource' 抛出异常;嵌套异常是 java.lang.IllegalStateException:无法加载驱动程序类: org.postgresql.Driver
如果我删除以下条目(即不要在 application.properties
中定义驱动程序,而只有 pom 依赖项):
spring.datasource.driverClassName=org.postgresql.Driver
然后我收到以下错误:
Failed to load driver class org.postgresql.Driver in either of HikariConfig class loader or Thread context classloader
答案 0 :(得分:0)
当我展开外部依赖树时,我没有找到 postgressql 的任何 jar。重新导入maven依赖后,添加正确,问题消失。现在好了。
答案 1 :(得分:0)
您不需要任何特定配置来连接数据库,除非您的存储库和实体包不是从另一个依赖项中提取的。
我建议您检查您的计算机和 Maven 存储库之间的连接。你应该以某种方式错过你的 postgre 依赖。
(您也可以尝试提供特定版本的 postgresql 工件)