Maven中dependencyManagement标签作用
- 在该元素下声明的依赖不会实际引入到模块中,只有在 dependencies 元素下同样声明了该依赖,才会引入到模块中。该元素能够约束 dependencies 下依赖的使用
- 即 dependencies 声明的依赖若未指定版本,则使用 dependencyManagement 中指定的版本,否则将覆盖 dependencyManager 中的版本
- dependencyManager 可以传递给子模块,所以在子模块中可以引用父模块 dependencyManagement 定义好的依赖
举例
使用 dependencyManagement 声明依赖
<!--在dependencyManagement 声明的依赖不会实际引入到模块中 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.5</version>
</dependency>
</dependencies>
</dependencyManagement>
如果需要使用该依赖,则应该在 dependencies 中重新声明该依赖
<!--如果需要使用,在dependencies中声明该依赖,无须指定版本-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
如果是在子类中,需要先引入父模块,再引用依赖
<!--引入父模块, parent标签可以理解为java中的继承关系-->
<parent>
<groupId>父类 groupId</groupId>
<artifactId>父类 artifactId</artifactId>
<version>父类 version</version>
</parent>
<!--如果需要使用,在dependencies中声明该依赖,无须指定版本-->
<dependencies>
<dependency>
<!--如果指定了版本号,则会覆盖父模块 dependencyManagement 定义的版本(不建议这
做,dependencyManagement的作用本来就是用来统一版本,防止依赖冲突)-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
总结
使用 dependencyManagement 可以统一声明依赖版本,进行集中管理,避免依赖冲突