Spring项目部署Heroku遇Maven编译错误:无效目标版本11
将Spring项目通过Maven Wrapper部署到Heroku时编译失败,报错信息如下:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project xyz: Fatal error compiling: invalid target release: 11 -> [Help 1]
remote: [ERROR]
remote: [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
remote: [ERROR] Re-run Maven using the -X switch to enable full debug logging.
remote: [ERROR]
remote: [ERROR] For more information about the errors and possible solutions, please read the following articles:
remote: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
remote:
remote: ! ERROR: Failed to build app with Maven
remote: We're sorry this build is failing! If you can't find the issue in application code,
remote: please submit a ticket so we can help: https://help.heroku.com/
remote:
remote: ! Push rejected, failed to compile Java app.
remote:
remote: ! Push failed
环境信息
- 本地:JDK 1.8.0_382(JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64)、Maven 3.6.3,本地编译运行正常
- Heroku:部署时自动安装OpenJDK 1.8和Maven 3.9.4,但仍触发编译错误
POM.xml关键配置片段
<properties> <java.runtime.version>11</java.runtime.version> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>
- Spring Boot父工程配置冲突:
spring-boot-starter-parent会通过标准属性java.version自动配置编译版本,你使用的java.runtime.version不是Spring Boot识别的属性,导致父工程的隐含配置覆盖了自定义的compiler插件设置,最终编译目标版本被设为11。 - Maven版本解析差异:Heroku使用的Maven 3.9.4与本地3.6.3在配置优先级处理上存在差异,导致自定义的编译版本配置未生效。
1. 修正POM中的Java版本属性
将非标准的java.runtime.version替换为Spring Boot认可的java.version,确保全局版本统一:
<properties> <java.version>1.8</java.version> </properties>
2. 强制生效编译插件配置
显式指定compiler插件版本,并绑定到统一的Java版本属性,同时开启强制fork编译确保使用指定JDK:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <fork>true</fork> <executable>${java.home}/bin/javac</executable> </configuration> </plugin>
3. 告诉Heroku明确使用JDK8
在项目根目录创建system.properties文件,添加以下内容:
java.runtime.version=1.8
Heroku会优先读取该文件确定JDK版本,避免自动选择时的冲突。
4. 清理后重新部署
- 本地执行
mvn clean install确保编译无问题 - 清理Git缓存避免旧配置残留:
git rm -r --cached . && git add . && git commit -m "Fix Java version configuration" - 推送代码到Heroku:
git push heroku main
内容的提问来源于stack exchange,提问作者edwesh

