在微服务项目中,绕不开的问题就是依赖,在依赖管理中dependency和dependencyManagement是两个十分重要的标签,下面介绍这俩标签的区别与使用。
dependencies
在这个标签下你可以放很多的dependency由Maven帮你控制依赖的生成
比如
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
你在父工程下写的dependencies依赖,在子工程下将可以直接使用(无需在xml配置文件中引入),且版本统一(版本由父工程引入依赖时指定)
dependencyManagement
dependecnyManagement也是用于管理依赖
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version> 1.18.20</version>
</dependency>
</dependencies>
</dependencyManagement>
子项目引入依赖的时候只需写groupId和artifactId即可,版本号将会自动和父项目的保持一致, 如果子项目里不写,则不会自动引入
二者的关系
包含、并列、互补 是二者关系的体现。
这在实际使用过程中有所体现,可以证明以上三点。
下面是一个示例
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!--这里出现了dependencyManagement标签-->
<dependencyManagement>
<!--内部使用了dependecies标签,说明可以包含-->
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 这里出现了dependencies标签,说明可以并列 -->
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version> 1.18.20</version>
</dependency>
</dependencies>
</project>
包含
dependencyManagement标签里面可以写dependencies标签,且只能存在唯一的dependencies标签
并列
二者可以并列出现,并列出现的意义在于
- dependencyManagement可以存放
绝大多数子项目都需要的依赖
,写在父项目里,子项目直接引入而不需要考虑版本问题,对于不需要的子项目可以选择性引入。 - dependencies则可以用于指定
所有子项目都需要要的依赖
,在父项目里写了dependencies引入某个依赖指定版本,甚至在子项目中无需引入,直接可以使用。
倘若用dependencyManagement来处理所有子项目都需要的依赖,则需要在每个子项目的
dependencies里逐个引入
互补
从并列的属性中可以看出,dependencies,dependencyManagement其实是一个互补的关系,双方都完成了对方无法完成的功能,让依赖的管理更加合理。
希望你读过这篇文章对 dependencies,dependencyManagement的区别与使用 有了清晰的了解,谢谢。
Thanks for watching!💕