Maven中如何使用不同参数重复执行同一execution配置
解决方案
你可以通过Maven的pluginManagement+配置继承的组合方式实现需求,不需要重复复制全量execution配置:
第一步:在父POM中定义通用基础配置
在父模块的pluginManagement节点下配置exec-maven-plugin的通用execution模板,把可变参数用Maven属性占位:
<pluginManagement> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <id>exec-build-in-checks-base</id> <phase>verify</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>${java.exe}</executable> <workingDirectory>${project.build.directory}</workingDirectory> <arguments> <argument>-classpath</argument> <argument>${app.classpath}</argument> <argument>${app.mainClass}</argument> <argument>-someCommonArgument</argument> <argument>-anotherCommonArgument</argument> <argument>${module.dependent.arg}</argument> <argument>${unique.check.arg}</argument> </arguments> </configuration> </execution> </executions> </plugin> </plugins> </pluginManagement>
这里把someModuleDependentArgument对应的值定义为属性${module.dependent.arg},someUniqueArgument对应的值定义为属性${unique.check.arg}。
第二步:子模块复用基础配置,仅修改模块级可变参数
在需要使用该检查的子模块pom中,先定义模块专属的module.dependent.arg属性,然后直接引用父POM的基础execution,不需要重复写全量配置:
<properties> <!-- 仅修改模块专属参数 --> <module.dependent.arg>moduleA-special-value</module.dependent.arg> </properties> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <!-- 不需要写version,继承自pluginManagement --> <executions> <!-- 同模块下第一个检查执行 --> <execution> <!-- 继承父POM的基础配置,id和父定义的一致 --> <id>exec-build-in-checks-base</id> <!-- 可以不用重新写phase、goals,自动继承 --> <configuration> <!-- 仅修改本次执行的唯一参数即可 --> <properties> <unique.check.arg>first-check-value</unique.check.arg> </properties> </configuration> </execution> <!-- 同模块下第二个检查执行,仅改唯一参数 --> <execution> <!-- 换个新id,避免重复 --> <id>exec-build-in-checks-second</id> <!-- 显式指定继承自基础execution --> <inherited>true</inherited> <configuration> <properties> <unique.check.arg>second-check-value</unique.check.arg> </properties> </configuration> </execution> </executions> </plugin> </plugins> </build>
如果同模块需要执行更多次检查,只需要新增execution节点,换个新id,仅修改unique.check.arg属性即可,不需要重复写公共配置。
补充说明
这种方式所有执行都会在同一次verify阶段按顺序执行,不需要用到profile或者命令行传参,完全满足你同一次构建多次执行的需求。如果后续需要调整公共参数,只需要修改父POM的pluginManagement中的基础配置,所有子模块的执行都会自动生效。
内容的提问来源于stack exchange,提问作者Robert P
相关产品推荐
相关产品推荐

