Maven多模块项目使用profile时无法解析其他模块依赖包问题
问题根因
你犯了Maven多模块依赖配置最常见的定位错误:把模块自身的强依赖声明写到了其他模块的配置里。
- jar-module1自身的代码直接引用了jar-module2的类,说明jar-module1编译阶段就必须依赖jar-module2,这个依赖是jar-module1本身的固有属性,必须声明在jar-module1自己的pom.xml中。
- 你当前把jar-module1、jar-module2的依赖全部写在war-module的profile配置里,只有激活对应profile构建war-module时,Maven才会把对应依赖加入war的依赖树。但单独构建jar-module1、或者全量构建触发jar-module1编译时,jar-module1自身的pom中没有任何对jar-module2的依赖声明,Maven自然不会把jar-module2加入jar-module1的编译类路径,就会报包不存在的错误。
- IntelliJ IDEA不会严格校验依赖声明,只要是同项目下的模块,会自动把所有模块的编译输出加入类路径,所以IDEA里不会提示错误,这和纯Maven构建的逻辑完全不同。
解决方案
第一步:修正模块固有依赖
直接在jar-module1/pom.xml中硬编码声明对jar-module2的依赖,这是jar-module1编译的必要前提,不需要做任何动态配置:
<dependencies> <dependency> <artifactId>jar-module2</artifactId> <groupId>你的项目groupId</groupId> <version>${revision}</version> </dependency> </dependencies>
第二步:保留war模块的profile逻辑
war模块的原有profile不需要做太大调整,符合你切换依赖的需求:
- 激活
profile1时,war依赖jar-module1,会自动传递引入jar-module2 - 激活
profile2时,war直接依赖jar-module2,如果你需要完全避免jar-module1被其他配置传递引入,可以加排除规则:
<profile> <id>profile2</id> <dependencies> <dependency> <artifactId>jar-module2</artifactId> <groupId>你的项目groupId</groupId> <version>${revision}</version> <!-- 如果有需要可以添加exclusions标签排除传递依赖 --> </dependency> </dependencies> </profile>
可选优化(针对${revision}版本号)
因为你用了${revision}作为统一版本号,建议在根pom中添加flatten-maven-plugin配置,避免install、deploy时版本号占位符未解析的问题:
<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>flatten-maven-plugin</artifactId> <version>1.5.0</version> <executions> <execution> <id>flatten</id> <phase>process-resources</phase> <goals> <goal>flatten</goal> </goals> </execution> <execution> <id>flatten.clean</id> <phase>clean</phase> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
构建命令建议
如果需要只构建war模块及其依赖的上游模块,可以用如下命令,提高构建效率:
# 激活profile2构建war模块及所有依赖的上游模块 mvn clean package -Pprofile2 -pl module-group/war-module -am
内容的提问来源于stack exchange,提问作者Pavel Polyakoff
相关产品推荐
相关产品推荐

