You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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>

效果验证

修改后执行全量构建:

  1. C的依赖树中不再包含模块A
  2. C的jar仅包含重定位后的org.example.maventest.a.A
  3. 在C中引用原始org.example.maventest.A会编译失败,与单独构建C的行为一致

内容的提问来源于stack exchange,提问作者willkroboth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 22:29:58