Maven多模块构建:如何让子模块使用dependency-reduced-pom?
Maven多模块Shade依赖传递问题解决方案
问题背景
父模块MavenTest包含3个子模块A、B、C:
- 模块A包含类
org.example.maventest.A - 模块B通过maven-shade-plugin将A重定位为
org.example.maventest.a.A并打包 - 模块C依赖B,期望仅打包B中重定位后的类
预期:全量执行mvn clean install时,C的jar仅包含org.example.maventest.a.A
实际:全量构建时,C的jar同时包含原始org.example.maventest.A和重定位类;单独构建C(mvn clean install -pl :C)时符合预期,因为此时C使用了B的dependency-reduced-pom.xml(已移除对A的依赖)。
该问题还导致编译不一致:全量构建时C可引用原始A类,单独构建时则找不到类。
问题根源
全量构建采用Maven reactor模式,模块C直接依赖项目内的B模块,此时Maven使用B的原始pom.xml(保留了对A的依赖);而单独构建C时,Maven从本地仓库获取B的构件,此时使用的是B安装到仓库时生成的dependency-reduced-pom.xml——shade插件默认会生成该文件,移除已被打包进B的依赖(即A)。
解决方案
修改模块B的maven-shade-plugin配置,开启在reactor构建中使用dependency-reduced-pom.xml作为当前模块的pom,传递给依赖它的模块:
在B的pom.xml中,给shade插件的<configuration>添加以下配置:
<createDependencyReducedPom>true</createDependencyReducedPom> <useDependencyReducedPomInProject>true</useDependencyReducedPomInProject>
完整的B模块shade插件配置示例:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.6.0</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <relocations> <relocation> <pattern>org.example.maventest</pattern> <shadedPattern>org.example.maventest.a</shadedPattern> </relocation> </relocations> <!-- 新增配置 --> <createDependencyReducedPom>true</createDependencyReducedPom> <useDependencyReducedPomInProject>true</useDependencyReducedPomInProject> </configuration> </execution> </executions> </plugin>
效果验证
修改后执行全量构建:
- C的依赖树中不再包含模块A
- C的jar仅包含重定位后的
org.example.maventest.a.A - 在C中引用原始
org.example.maventest.A会编译失败,与单独构建C的行为一致
内容的提问来源于stack exchange,提问作者willkroboth
相关产品推荐
相关产品推荐

