Spring Boot+Gradle项目连接MySQL报错:无法加载com.mysql.cj.jdbc.Driver
解决Spring Boot连接MySQL时找不到驱动类的问题
问题核心
错误提示Cannot load driver class: com.mysql.cj.jdbc.Driver,说明你的项目缺少MySQL JDBC驱动依赖,Spring Boot无法加载数据库驱动类。
解决方案
1. 添加MySQL驱动依赖
在你的Gradle配置文件的dependencies块中,添加MySQL驱动的运行时依赖:
dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-jdbc' testImplementation 'org.springframework.boot:spring-boot-starter-test' // 添加MySQL驱动依赖 runtimeOnly 'mysql:mysql-connector-java' }
注:使用
runtimeOnly是因为驱动仅在运行时需要,Spring Boot的依赖管理会自动匹配与2.7.2版本兼容的驱动版本。
2. 验证数据库配置
确保application.properties或application.yml中的数据库配置正确,示例配置:
# application.properties spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名称?useSSL=false&serverTimezone=UTC spring.datasource.username=你的数据库用户名 spring.datasource.password=你的数据库密码 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 若使用MySQL 5.x版本,驱动类名需改为
com.mysql.jdbc.Driver,URL中的serverTimezone参数可省略。
3. 重新启动应用
保存配置后,再次执行启动命令:
gradlew.bat bootRun
内容的提问来源于stack exchange,提问作者Wlp Aminur
相关产品推荐
相关产品推荐

