原文地址(强烈建议看原文):https://www.jianshu.com/p/5b7296445a0e
Spring Cloud项目一般会搭建为Mavne多模块项目,常见到dependencyManagement,存在两种情况
一. 在父项目中的dependencyManagement
它是对所依赖jar包进行声明依赖,继承该父项目的子项目,不会直接引入dependencyManagement管理的jar包。因此子项目需要显式的声明需要用的依赖,并且没有指定version,才会从父项目中继承该依赖,这时version和scope都读取自父pom;
如果子项目中指定了版本号,那么会使用子项目中指定的jar版本.;
如果不在子项目中声明依赖,是不会从父项目中继承下来的;
而不包含在dependencyManagement中的dependencies中的依赖,即使在子项目中不写该依赖项,仍然会从父项目中继承该依赖项(全部继承)
如下
<!-- 会实际下载jar包,子项目会继承这些依赖 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<!-- 只是对版本进行管理,不会实际引入jar,子项目继承时必须显示声明,才会引入该依赖 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
</dependencies>
</dependencyManagement>
二. 子项目自身使用dependencyManagement
注意:此处 dependencyManagement 不是版本管理,而是导入多个父模块
这样的用法必须在当前pom中使用dependencyManagement 标签,并且添加上
<type>pom</type>和<scope>import</scope>标签
这是为了解决maven 单继承的问题,使用这种方式,子模块不仅可以继承parent标签中的模块,也可以继承dependencyManagement中的其它模块,如下
<!--当前模块同时继承spring-boot-starter-parent、spring-boot-dependencies 和 spring-cloud-dependencies-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath />
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.4.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
如果大家不知道spring-cloud的版本如何选择,可以参考这位哥们的
SpringBoot与SpringCloud的版本对应详细版