配置Testcontainers+R2DBC时抛出com.mysql.jdbc.Driver类找不到异常
解决Testcontainers + R2DBC连接MySQL时的ClassNotFoundException异常
异常原因
抛出java.lang.ClassNotFoundException: com.mysql.jdbc.Driver是因为项目触发了JDBC相关的初始化逻辑,但缺少MySQL的JDBC驱动依赖(com.mysql.jdbc.Driver属于mysql-connector-java包),你目前仅引入了R2DBC异步驱动,未添加JDBC驱动。
解决方案
方案1:若项目中用到JDBC(如SchemaCreatorConfig使用了DataSource/JdbcTemplate)
在pom.xml的test依赖中添加MySQL JDBC驱动:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>test</scope> </dependency>
方案2:若未用到JDBC,排除Spring Boot的JDBC自动配置
方式A:在测试类上直接排除
修改测试类的@SpringBootTest注解:
@SpringBootTest( webEnvironment = WebEnvironment.RANDOM_PORT, exclude = {DataSourceAutoConfiguration.class, JdbcTemplateAutoConfiguration.class} ) @ActiveProfiles(profiles = "it") @Testcontainers @TestInstance(Lifecycle.PER_CLASS) @Import(SchemaCreatorConfig.class) public class WarehouseControllerIT { // 测试代码不变 }
方式B:通过配置文件排除
在application-it.yml中添加自动配置排除项:
spring: r2dbc: url: r2dbc:tc:mysql:///warehouse-db?TC_IMAGE_TAG=latest autoconfigure: exclude: - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration - org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
补充说明
Testcontainers的R2DBC集成本身不需要JDBC驱动,但如果Spring Boot自动配置检测到JDBC相关类(比如依赖间接引入),会尝试初始化JDBC数据源,进而触发JDBC驱动的查找,最终导致异常。排除JDBC自动配置或添加对应驱动即可解决问题。
内容的提问来源于stack exchange,提问作者fun_and_sun
相关产品推荐
相关产品推荐

