如何仅为测试代码开启Maven增量编译功能?
实现方案
可以实现该需求,无需引入额外插件,直接通过maven-compiler-plugin的目标级独立配置即可完成。maven-compiler-plugin存在两个独立的编译目标:compile用于编译src目录下的主业务代码,testCompile用于编译tests目录下的测试代码,两个目标支持分别配置增量编译参数。
配置示例
<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> <encoding>${project.build.sourceEncoding}</encoding> </configuration> <executions> <!-- 主代码编译专属配置 --> <execution> <id>default-compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> <configuration> <!-- 主代码关闭增量编译 --> <useIncrementalCompilation>false</useIncrementalCompilation> </configuration> </execution> <!-- 测试代码编译专属配置 --> <execution> <id>default-testCompile</id> <phase>test-compile</phase> <goals> <goal>testCompile</goal> </goals> <configuration> <!-- 测试代码开启增量编译 --> <useIncrementalCompilation>true</useIncrementalCompilation> </configuration> </execution> </executions> </plugin>
注意事项
- 增量编译依赖上一次构建生成的缓存产物,你当前使用的
mvn clean install命令中clean会清空target目录下的所有缓存内容,会导致增量编译失效。日常开发可以去掉clean参数执行构建,仅在需要全量编译时再添加该参数。 - 你当前使用的maven-compiler-plugin 3.1版本已适配Java 1.8、Apache Maven 3.8.2环境,无需升级插件即可正常使用上述配置。
内容的提问来源于stack exchange,提问作者John Doe
相关产品推荐
相关产品推荐

