Maven的POM文件相关标签作用

在Maven的POM文件中,<dependencies> 和 <dependencyManagement> 是两个相关但用途不同的标签,主要区别如下:

<dependencies>(直接依赖声明)

  • 立即生效:在此标签中声明的依赖会被直接引入到当前项目中

  • 自动下载:Maven会立即下载这些依赖到本地仓库

  • 传递性依赖:这些依赖的传递性依赖也会被自动引入

xml

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.8</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>(依赖管理)

  • 仅声明版本:在此标签中声明的依赖不会立即被引入项目

  • 版本统一管理:主要用于在父POM中统一管理依赖版本

  • 子模块继承:子模块引用这些依赖时无需指定版本号

父POM中的用法:

xml

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

子模块中的用法:

xml

<dependencies>
    <!-- 无需指定版本,从父POM继承 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
    </dependency>
</dependencies>

主要区别总结

特性<dependencies><dependencyManagement>
作用直接引入依赖管理依赖版本
是否下载立即下载不下载,仅声明
使用场景单个模块多模块项目的父POM
版本管理每个依赖需指定版本统一管理版本,子模块继承
传递性有传递性依赖无传递性

最佳实践

  • 在多模块项目中使用<dependencyManagement>统一管理依赖版本

  • 在子模块的<dependencies>中只需声明需要的依赖,版本从父POM继承

  • 这样可以确保整个项目使用统一的依赖版本,避免版本冲突

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值