1、dependencyManagement

对于dependencyManagement,我们首先想到的就是统一管理版本
例如:
在父pom文件中声明spring-context的版本为5.3.18

  1. <dependencyManagement>
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework</groupId>
  5. <artifactId>spring-context</artifactId>
  6. <version>5.3.18</version>
  7. </dependency>
  8. </dependencies>
  9. </dependencyManagement>

然后在子pom文件中引入,并且不用定义版本号,会自动使用父pom中定义的版本

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. </dependency>
  6. </dependencies>

实际导入的jar包如下
image.png

2、dependencyManagement其实也可以管理依赖项下自带的其他依赖的版本

举个例子:
A依赖B,B依赖C,在项目A中引入B的依赖,会自动导入依赖C,且版本是v1
A——》B——》C(v1)
这时,如果在A中加入dependencyManagement或者A的父POM中使用dependencyManagement管理C的版本为v2

  1. <dependencyManagement>
  2. <dependencies>
  3. <dependency>
  4. <groupId>xxx</groupId>
  5. <artifactId>C</artifactId>
  6. <version>v2</version>
  7. </dependency>
  8. </dependencies>
  9. </dependencyManagement>

此时A项目中引入的C项目的jar包版本就是v2了,而不是B中声明的v1版本

例如:
在父pom中管理了这么一个依赖:spring-core,版本是5.1.8.RELEASE

  1. <dependencyManagement>
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework</groupId>
  5. <artifactId>spring-core</artifactId>
  6. <version>5.1.8.RELEASE</version>
  7. </dependency>
  8. </dependencies>
  9. </dependencyManagement>

现在在子pom中有这么一个依赖:spring-context,版本是5.3.18

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.3.18</version>
  6. </dependency>
  7. </dependencies>

spring-context,版本是5.3.18,下面又有这些依赖:里面的spring-core的版本也是5.3.18
image.png
这时也许你认为实际导入也应该是5.3.18的spring-core包,但实际上却是:5.1.8.RELEASE
image.png
这是因为dependencyManagement可以管理依赖项中引入其他附带的jar包的版本
就算只是在子pom中的dependencyManagement中加入版本管理,同样可以管理依赖项下引进的其他jar包版本
例如:
image.png
此时的版本也同样是5.1.8.RELEASE
image.png