Java 17中Maven Compiler搭配--release时导出jdk.compiler包报错
解决maven-compiler-plugin添加add-exports参数时的编译错误
错误原因
你遇到的exporting a package from system module jdk.compiler is not allowed with --release错误,本质是JDK的限制:当编译时使用--release参数(用于指定兼容的Java版本),JDK会禁止导出系统模块(比如jdk.compiler)的内部包,因为--release模式下会严格遵循目标版本的模块访问规则。
即使你注释了配置里的<release>标签,高版本的maven-compiler-plugin(3.8.0及以上)如果同时设置了maven.compiler.source和maven.compiler.target为同一版本,会自动启用--release参数,替代传统的-source和-target,这就导致了错误触发。
解决方案
方案1:改用Google Java Format的官方Maven插件(推荐)
你不需要在maven-compiler-plugin里手动添加这些模块导出参数,Google Java Format有专门的Maven插件,集成更简单且不会触发此类问题:
<plugin> <groupId>com.google.googlejavaformat</groupId> <artifactId>google-java-format-maven-plugin</artifactId> <version>1.17.0</version> <executions> <execution> <id>format</id> <goals> <goal>format</goal> </goals> <phase>process-sources</phase> </execution> </executions> </plugin>
执行mvn google-java-format:format即可格式化代码,或者绑定到构建阶段自动执行。
方案2:禁用maven-compiler-plugin的--release参数
如果必须保留当前的编译器参数配置,需要明确禁用--release:
- 在
maven-compiler-plugin的配置中,替换<release>为<source>和<target>,并显式设置<release>false</release>来禁用自动启用的--release:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.compiler.version}</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <release>false</release> <!-- 禁用自动--release --> <compilerArgs> <arg>--add-opens=java.base/java.lang=ALL-UNNAMED</arg> <arg>--add-opens=java.base/java.util=ALL-UNNAMED</arg> <arg>--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED</arg> <arg>--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED</arg> <arg>--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED</arg> <arg>--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED</arg> <arg>--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED</arg> <arg>--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED</arg> <arg>--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED</arg> </compilerArgs> </configuration> </plugin>
- 或者降低
maven-compiler-plugin版本到3.7.1及以下,这些版本不会自动启用--release参数。
方案3:检查其他配置是否触发--release
确保你的pom.xml或settings.xml中没有全局设置maven.compiler.release属性,该属性也会强制启用--release模式。
内容的提问来源于stack exchange,提问作者Bilgehan
相关产品推荐
相关产品推荐

