【爬坑记录】Failed to determine a suitable driver class

SpringBoot项目启动失败:Failed to determine a suitable driver class

【爬坑记录】Failed to determine a suitable driver class

  • 关键字:dataSourceFailed to determine a suitable driver classcom.zaxxer.hikari.HikariDataSource

问题描述

创建 SpringBoot 项目的时候,添加了 mysqlmybatis 依赖,直接启动出现了一个很有意思的错误(之前也有过),后续只能先配置本地数据库再去启动项目。今年想了一下,Spring 不可能每次都要数据库才能访问接口,如果没有数据库可咋整啊,于是乎,决定盘他。

解决方案

先给解决方案,再谈细节。

    1. 既然初始化 HikariDataSource 失败,那就不要初始化。解决办法只需要在 Application.class排除数据库配置类即可
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
    1. application.yaml 配置完整的数据库信息
    1. 去除 pom.xml 文件中的数据库相关依赖
完整的报错日志

如果 Console 没有打印日志的话,可以在 Application.class 对 SpringApplication.run() 方法进行异常捕获。

报错日志如下:

log4j:WARN No appenders could be found for logger (org.springframework.boot.env.OriginTrackedYamlLoader).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.1)

四月 26, 2022 8:24:26 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Tomcat]
四月 26, 2022 8:24:26 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet engine: [Apache Tomcat/9.0.55]
四月 26, 2022 8:24:26 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring embedded WebApplicationContext
四月 26, 2022 8:24:27 下午 org.apache.catalina.core.StandardService stopInternal
信息: Stopping service [Tomcat]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658)
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730)
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:302)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290)
	at wiki.laona.Application.main(Application.java:17)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
	... 19 more
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
	at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:252)
	at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:193)
	at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:48)
	at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari.dataSource(DataSourceConfiguration.java:90)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
	... 20 more

Process finished with exit code 0

整个日志看下来就是因为没有配置 DataSource 导致SpringBoot 项目启动失败。

### 错误原因分析 在数据库连接过程中,出现“Failed to determine a suitable driver class”错误通常是由于以下原因之一导致的[^1]: - 数据库驱动程序未正确加载或不存在。 - 提供的 JDBC URL 格式不正确,无法匹配到合适的驱动程序。 - 配置文件中缺少必要的驱动类名或配置参数。 - 使用了过时的 `DriverManager` 而未正确利用服务提供者机制(Service Provider Mechanism)。 例如,在使用 DBCP 2 或其他连接池时,如果没有正确指定 `driverClassName` 或者驱动程序未被加载到类路径中,则会引发此错误[^2]。 ### 解决方案 #### 1. 确保驱动程序已正确加载 确保数据库驱动程序 JAR 文件已被添加到项目的类路径中。例如,对于 MySQL 数据库,需要将 `mysql-connector-java` 的 JAR 文件包含在项目依赖中。如果使用 Maven,可以在 `pom.xml` 中添加以下依赖项: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.30</version> </dependency> ``` #### 2. 检查 JDBC URL 和驱动类名 确保 JDBC URL 和驱动类名匹配。以下是一些常见数据库的配置示例: - **MySQL**: ```properties jdbc:mysql://localhost:3306/mydatabase com.mysql.cj.jdbc.Driver ``` - **PostgreSQL**: ```properties jdbc:postgresql://localhost:5432/mydatabase org.postgresql.Driver ``` 如果使用的是 DBCP 2,可以通过设置 `BasicDataSource` 的属性来指定驱动类名和 URL[^2]: ```java BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase"); dataSource.setUsername("root"); dataSource.setPassword("password"); ``` #### 3. 避免使用过时的 `DriverManager` 现代数据库连接池(如 DBCP 2、HikariCP)通常不需要显式指定驱动类名,因为它们可以自动检测驱动程序。如果仍然遇到问题,可以尝试省略 `driverClassName` 并仅依赖 JDBC URL[^1]。 #### 4. 检查日志和异常堆栈 通过查看详细的日志信息,可以进一步定位问题。例如,某些驱动程序可能需要额外的依赖项或配置参数。检查日志输出以确认驱动程序是否成功加载以及 JDBC URL 是否解析正确。 #### 5. 更新驱动程序版本 如果使用的驱动程序版本较旧,可能会与当前数据库或连接池不兼容。建议更新到最新稳定版本的驱动程序,并确保其与数据库版本匹配。 ### 示例代码 以下是一个完整的 DBCP 2 配置示例,用于避免“Failed to determine a suitable driver class”错误: ```java import org.apache.commons.dbcp2.BasicDataSource; public class DatabaseConnectionExample { public static void main(String[] args) { try { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); // 设置驱动类名 dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase"); // 设置 JDBC URL dataSource.setUsername("root"); // 设置用户名 dataSource.setPassword("password"); // 设置密码 // 测试连接 try (var connection = dataSource.getConnection()) { System.out.println("Database connection successful!"); } } catch (Exception e) { e.printStackTrace(); } } } ``` ### 注意事项 - 如果使用的是 Spring Boot 或其他框架,通常可以通过配置文件(如 `application.properties` 或 `application.yml`)简化数据库连接配置。 - 在生产环境中,建议使用更高效的连接池(如 HikariCP)替代 DBCP 2。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值