Maven测试失败:无法访问jdk.compiler模块的com.sun.tools.javac.api包
问题分析与解决方案
你遇到的核心问题是:仅给编译阶段配置了模块访问参数,但测试运行阶段未传递对应参数。maven-compiler-plugin的配置只作用于代码编译环节,而测试用例的运行由maven-surefire-plugin负责,当前测试进程的JVM没有获得--add-exports/--add-opens权限,因此触发了模块访问限制报错。
具体解决步骤
1. 升级maven-compiler-plugin版本
你使用的3.8.1版本对JDK22的支持不完善,建议升级到适配JDK22的稳定版本(如3.12.1),避免兼容性问题。
2. 给maven-surefire-plugin添加测试JVM参数
在pom.xml的build/plugins节点下,新增测试插件的配置,将模块访问参数传递给测试运行的JVM进程:
<build> <plugins> <!-- 编译插件配置 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.12.1</version> <configuration> <source>22</source> <target>22</target> <fork>true</fork> <compilerArgs> <arg>--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED</arg> </compilerArgs> </configuration> </plugin> <!-- 测试插件配置 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> <configuration> <argLine> --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED </argLine> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies>
配置说明
- 编译插件中的
--add-exports是给javac编译器用的,确保编译阶段能访问jdk.compiler模块的内部类; - 测试插件的
argLine是给运行测试用例的JVM进程设置参数,这里的--add-exports保证测试代码能访问目标类,--add-opens则是如果存在反射访问需求时的必要配置; - 移除了原配置中冗余的
-J--add-exports参数,-J前缀是传递给编译器进程的JVM参数,当前场景下直接使用--add-exports即可满足编译需求。
完成配置后,执行mvn clean test即可正常运行测试用例。
内容的提问来源于stack exchange,提问作者Yann-Gaël Guéhéneuc
相关产品推荐
相关产品推荐

