Maven中指定JDK编译版本的核心是控制source(源码语法)和target(字节码兼容性),最可靠方式是在pom.xml中用properties声明(如maven.compiler.source=17、target=17)或显式配置maven-compiler-plugin插件;settings.xml配置仅限本地、不推荐用于团队协作。

在 Maven 中指定 JDK 编译版本,核心是控制源码语法支持(source)和生成字节码兼容性(target),不是切换系统 JDK 路径。最可靠、最常用的方式是在项目 pom.xml 中配置,而非依赖全局设置。
用 properties 统一声明(推荐,简洁且可继承)
适合单模块或父子多模块项目,父 POM 写一次,子模块自动生效。Maven 3.8+ 默认识别这些属性,无需额外插件声明。
- 在
<project>标签下添加<properties>块:
<properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <maven.compiler.encoding>UTF-8</maven.compiler.encoding> </properties>
-
source=17表示允许使用 Java 17 语言特性(如 sealed 类、switch 表达式); -
target=17表示生成的 class 文件只能在 JDK 17 及以上运行时加载; - 若需向下兼容(如用 Java 21 写代码但部署到 JDK 17 环境),可设
source=21+target=17,但源码中不能调用 JDK 17 之后新增的 API。
显式配置 maven-compiler-plugin(更精细、更可控)
当你需要指定插件版本、启用 fork、跳过测试编译、开启详细日志等时,应显式声明插件。
- 在
<build><plugins>中添加完整插件配置:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.12.0</version>
<configuration>
<source>17</source>
<target>17</target>
<encoding>UTF-8</encoding>
<fork>true</fork>
</configuration>
</plugin>
- 推荐使用较新版本(如 3.12.0),避免老版本默认
source/target=1.5导致编译失败; -
fork=true是启用executable或 JVM 参数的前提; - 若需强制使用特定 JDK 的
javac(例如多 JDK 环境下隔离编译器),可配合<executable>和maven-toolchains-plugin使用,但日常开发极少需要。
不推荐的“全局”方式:settings.xml 配置
虽然可在 ~/.m2/settings.xml 的 profile 中设 maven.compiler.source,但它仅影响本地用户、不随项目提交、无法被团队共享,且容易与项目内配置冲突。
- 仅适用于个人快速验证场景,不适合协作项目;
- 一旦 pom.xml 中有同名 property 或 plugin 配置,会覆盖 settings.xml 的值;
- IDE(如 IntelliJ)通常优先读取 pom.xml,settings.xml 的效果常不可见。
验证是否生效
配置完后务必执行以下操作之一,让变更生效:
- 命令行运行:
mvn clean compile,观察编译输出是否含 Java 17 字节码信息; - IDE 中右键项目 → “Maven” → “Update project”(Eclipse/IntelliJ);
- 检查编译后的
target/classes/xxx.class:用javap -verbose xxx.class | grep "major",Java 17 对应 major version 61。


















