dependencies 与 dependencyManagement 区别

在 Maven 项目中,dependenciesdependencyManagement 都用于定义项目的依赖关系,但它们的使用场景和功能有所不同。以下是它们的主要区别:

dependencies

  • 位置: 位于 pom.xml 文件的 <dependencies> 元素内。
  • 作用: 直接定义项目的依赖项,表示这些依赖项将被包含在构建中。
  • 范围: 这些依赖项会被直接添加到当前项目的类路径中,并且会传递给下游模块(如果当前项目是一个父模块)。
  • 例子:
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.10</version>
        </dependency>
        <!-- 其他依赖项 -->
    </dependencies>
    

dependencyManagement

  • 位置: 位于 pom.xml 文件的 <dependencyManagement> 元素内,通常在父 POM 或顶级 POM 中。
  • 作用: 管理依赖项版本,提供版本控制和统一依赖版本声明,但不直接包含这些依赖项在构建中。
  • 范围: 这些依赖项需要在子模块的 <dependencies> 元素中显式声明才能生效。子模块可以引用这些依赖项而不需要指定版本号。
  • 例子:
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>5.3.10</version>
            </dependency>
            <!-- 其他依赖项 -->
        </dependencies>
    </dependencyManagement>
    

使用场景对比

  • dependencies: 适用于直接声明当前项目所需的所有依赖项。所有声明在 <dependencies> 中的依赖项会在构建时自动包含。
  • dependencyManagement: 适用于需要统一管理多个子项目(模块)依赖项的版本时。可以在父 POM 中声明所有子项目的依赖版本,子项目只需在自己的 <dependencies> 中引用这些依赖项,而不需要指定版本号。

综合示例

假设有一个父项目 parent 和两个子项目 child1child2

父项目 parentpom.xml:

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>parent</artifactId>
    <version>1.0.0</version>
    <packaging>pom</packaging>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>5.3.10</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

子项目 child1pom.xml:

<project>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>parent</artifactId>
        <version>1.0.0</version>
    </parent>
    <artifactId>child1</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <!-- 无需指定版本号 -->
        </dependency>
    </dependencies>
</project>

在这个例子中,child1 项目会包含 spring-core 依赖项,版本为 5.3.10,即使在其 pom.xml 中未指定版本号。这是因为 spring-core 的版本在父项目 parentdependencyManagement 中进行了统一管理。

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丢了尾巴的猴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值