在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继承 -
这样可以确保整个项目使用统一的依赖版本,避免版本冲突
1万+

被折叠的 条评论
为什么被折叠?



