You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot编写JPA单元测试时ApplicationContext加载失败

Spring Boot 2.7.0 JPA单元测试启动失败提示无法加载com.mysql.cj.jdbc.Driver解决

问题复现环境

  • 基础技术栈:Spring Boot 2.7.0、Spring Data JPA、JDK 17
  • 已引入依赖:spring-boot-starter-data-jpa、spring-boot-devtools、spring-boot-starter-test
  • 触发场景:编写testCreateCustomer单元测试方法,构造绑定2个PhoneNumber关联实体的Customer对象,调用repository.save()执行持久化操作时,测试直接抛出异常
  • 异常定位:沿异常栈逐层排查,确认Hikari连接池初始化阶段无法加载com.mysql.cj.jdbc.Driver驱动类,最终导致Spring应用上下文加载失败,测试用例终止执行

核心异常信息

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource: Failed to instantiate com.zaxxer.hikari.HikariDataSource
Caused by: java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

根因说明

spring-boot-starter-data-jpa仅包含JPA接口规范、Hibernate实现、Hikari连接池组件,不会自动引入特定数据库的驱动包,当前项目未显式引入MySQL官方JDBC驱动,导致连接池初始化时找不到对应的驱动类。

修复步骤

  1. 在pom.xml的依赖节点中添加MySQL驱动依赖,Spring Boot 2.7.x版本内置了该驱动的版本仲裁,不需要手动指定版本号,默认引入适配的8.x版本驱动,正好匹配com.mysql.cj.jdbc.Driver驱动类:
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

注意:不要引入旧版mysql:mysql-connector-java 5.x版本依赖,该版本的驱动类路径为com.mysql.jdbc.Driver,和当前配置的驱动类不匹配,会继续报类找不到错误
2. 核对配置文件中的数据源参数,确保驱动类名、连接地址、账号密码配置正确,application.yml参考配置如下:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/你的业务库名?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true
    username: 数据库账号
    password: 数据库密码
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true

如果单元测试使用独立的测试配置文件(如application-test.yml),需要同步保证该配置文件中的数据源参数正确。如果不需要对接真实MySQL做测试,可以引入H2内存数据库作为测试数据源,仅在test作用域引入依赖即可,无需额外安装数据库服务:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>
  1. 依赖添加完成后,刷新Maven依赖拉取对应jar包,执行mvn clean清理旧的构建缓存,重新运行单元测试即可。

内容的提问来源于stack exchange,提问作者Gyanendra Mohan Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 18:33:30