如何在Spring Boot的pom文件中配置JVM参数解决集成测试报错?
正确配置方式
要让--add-opens java.base/java.nio=ALL-UNNAMED在mvn clean install的测试阶段生效,需要配置maven-surefire-plugin的argLine参数——因为集成测试(包括@SpringBootTest)是由Maven Surefire插件负责执行的,和spring-boot-maven-plugin无关。
具体POM配置如下:
<build> <plugins> <!-- 配置Surefire插件,为测试阶段添加JVM参数 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> <!-- 建议使用最新稳定版 --> <configuration> <argLine>--add-opens java.base/java.nio=ALL-UNNAMED</argLine> </configuration> </plugin> </plugins> </build>
为什么之前的配置无效?
- spring-boot-maven-plugin的jvmArguments:这个参数仅用于
spring-boot:run命令启动Spring Boot应用时的JVM参数,和测试阶段的执行逻辑不相关。 - 直接用-D参数:
--add-opens是JVM的选项参数,不是系统属性,不能用-D前缀传递,必须通过Surefire的argLine直接指定。
如果需要同时添加多个JVM参数,直接在argLine中用空格分隔即可,例如:
<argLine>--add-opens java.base/java.nio=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED</argLine>
内容的提问来源于stack exchange,提问作者Chetan
相关产品推荐
相关产品推荐

