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

执行mvn spring-boot:run/mvn clean install时编译错误求助

解决Maven编译错误:invalid target release: 17

问题根源

直接运行main方法正常,但Maven命令报错,核心原因是Maven使用的JDK版本与项目指定的Java 17不匹配。IDE运行main时调用的是IDE配置的JDK,而Maven默认读取系统环境变量JAVA_HOME或自身配置文件中的JDK路径,若该JDK版本低于17,就会触发此编译错误。

解决方案

以下按优先级从易到难列出解决方法:

1. 检查并配置系统环境变量JAVA_HOME

  • 确认本地已安装Java 17,找到其安装路径
  • 修改系统环境变量JAVA_HOME,指向Java 17的安装目录
  • 重启终端/命令行窗口,执行java -version和mvn -v确认版本均为17

2. 在Maven全局配置文件中指定JDK版本

若不想修改系统全局环境变量,可修改Maven的settings.xml文件(路径通常为~/.m2/settings.xml或Maven安装目录下的conf/settings.xml),添加如下配置:

<profiles>
    <profile>
        <id>jdk-17</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <maven.compiler.source>17</maven.compiler.source>
            <maven.compiler.target>17</maven.compiler.target>
            <maven.compiler.compilerVersion>17</maven.compiler.compilerVersion>
        </properties>
    </profile>
</profiles>

3. 在项目pom.xml中显式配置maven-compiler-plugin

虽然Spring Boot父pom已做基础配置,但显式指定插件参数可避免歧义,修改pom.xml的build/plugins部分:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.10.1</version>
            <configuration>
                <source>17</source>
                <target>17</target>
                <fork>true</fork>
                <executable>${JAVA_HOME}/bin/javac</executable>
            </configuration>
        </plugin>
    </plugins>
</build>

其中<fork>true</fork>和<executable>会强制Maven使用指定的JDK进行编译。

4. 检查IDE的Maven运行配置(若通过IDE执行Maven命令)

如果是在IDE内运行Maven命令,需确认IDE的Maven配置使用的JDK版本:

  • IDEA:打开File > Settings > Build, Execution, Deployment > Build Tools > Maven > Runner,在JRE选项中选择Java 17
  • Eclipse:打开Window > Preferences > Maven > Installations,确认Maven关联的JRE为Java 17

验证

修改完成后,执行mvn clean install或mvn spring-boot:run,若不再出现invalid target release:17错误,说明问题已解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:45:35