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

Maven 3.9.0传递依赖版本管控示例及疑问解答

Maven 3.9.0 dependencyManagement 管控传递依赖版本的明确解答

核心结论

  • 项目A最终引入的C版本是v2.0
  • 不需要将C添加到<dependencies>节点中,dependencyManagement会直接覆盖传递依赖的版本

示例配置

项目B的pom.xml(依赖C v1.0)

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>project-b</artifactId>
    <version>1.0.0</version>

    <dependencies>
        <!-- 项目B直接依赖C v1.0 -->
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>project-c</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
</project>

项目A的pom.xml(依赖B,通过dependencyManagement指定C v2.0)

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>project-a</artifactId>
    <version>1.0.0</version>

    <!-- 管控依赖版本 -->
    <dependencyManagement>
        <dependencies>
            <!-- 指定C的版本为2.0.0 -->
            <dependency>
                <groupId>com.example</groupId>
                <artifactId>project-c</artifactId>
                <version>2.0.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- 项目A直接依赖B -->
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>project-b</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
</project>

验证方法

在项目A的根目录执行Maven命令查看依赖树:

mvn dependency:tree

输出结果中会显示com.example:project-c:jar:2.0.0,而非1.0.0,证明版本已被dependencyManagement覆盖。

原理说明

Maven 3.9.0中,dependencyManagement的核心作用是统一管控所有依赖的版本——不管依赖是项目直接声明的,还是通过其他依赖传递过来的,只要在dependencyManagement中指定了对应构件的版本,Maven就会优先使用这个版本,直接覆盖传递依赖自带的版本,无需在<dependencies>中重复声明该依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:58:28