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

Spring Boot打包Jar运行报错:Failed to determine a suitable driver class

解决方案

1. 检查MySQL驱动依赖的Scope配置

别把驱动依赖的scope设为provided或test,这两类依赖不会被打包进最终Jar。正确配置参考:

  • Spring Boot 2.x版本:
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
  • Spring Boot 3.x版本(需使用新的驱动groupId):
<dependency>
    <groupId>com.mysql.cj</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

2. 核对application.properties的数据库配置

打包后Jar读取的配置可能和IDE环境存在差异,重点检查:

  • spring.datasource.url格式:MySQL 8.x必须添加时区参数,示例:jdbc:mysql://localhost:3306/your_db?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
  • 明确指定驱动类:MySQL 8.x用spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver,5.x版本用com.mysql.jdbc.Driver
  • 确认spring.datasource.username和spring.datasource.password无拼写错误

3. 验证Jar包是否包含驱动类

解压生成的Jar文件,查看BOOT-INF/lib目录下是否存在MySQL驱动Jar(如mysql-connector-java-xxx.jar)。如果缺失,说明Maven打包时未引入该依赖,检查pom.xml的<packaging>是否为jar,以及是否误排除了驱动依赖。

4. 排查自动配置是否被干扰

如果自定义了DataSource配置类,避免覆盖自动配置逻辑,或在配置类中手动指定驱动类。同时检查启动类是否添加了@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)这类注解,该注解会禁用数据库自动配置,导致驱动加载失败。

5. 使用Spring Boot插件打包

不要直接执行mvn package,改用Spring Boot专属插件打包,确保生成可执行Jar:

mvn spring-boot:package

也可以在pom.xml中提前配置插件:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

6. 检查启动时的外部配置干扰

启动Jar时是否通过命令行指定了其他配置文件?比如java -jar your-app.jar --spring.config.location=/path/to/other.properties,如果外部配置的数据库参数错误,也会触发该异常。确保启动使用的配置与IDE环境一致。

内容的提问来源于stack exchange,提问作者SaeedTheThird

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:42:52