首页 > 解决方案 > SpringBoot:无法加载驱动程序类:org.postgresql.Driver

问题描述

我刚刚创建了一个新的 SpringBoot 应用程序(Java11)并试图连接到 Postgres 数据库。

当我启动 SpringBoot 应用程序时,尝试连接数据库时出错。错误报告它Cannot load driver class: org.postgresql.Driver

问题

如何更改下面的配置以使 SpringBoot 应用程序连接到数据库?

数据库版本

x86_64-apple-darwin16.7.0 上的 PostgreSQL 12.6,由 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>

应用程序属性

# 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 --- [main] osboot.SpringApplication
:应用程序运行失败

org.springframework.beans.factory.UnsatisfiedDependencyException:在类路径资源 [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class] 中定义名称为“dataSourceScriptDatabaseInitializer”的 bean 创建错误:通过方法“dataSourceScriptDatabaseInitializer”参数表示的依赖关系不满足0; 嵌套异常是 org.springframework.beans.factory.BeanCreationException:在类路径资源 [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class] 中定义名称为“dataSource”的 bean 创建时出错:通过工厂方法进行 Bean 实例化失败; 嵌套异常是 org.springframework.beans.BeanInstantiationException:无法实例化 [com.zaxxer.hikari.HikariDataSource]:工厂方法 'dataSource' 抛出异常;

如果我删除以下条目(即不定义驱动程序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

标签: postgresqlspring-bootjpa

解决方案


当我扩展外部依赖树时,我没有找到 postgressql 的任何 jar。重新导入maven依赖后,它被正确添加并且问题消失了。现在很好。


推荐阅读