使用spring Initializr创建了一个spring cloud项目,会发现原来的<parent>标签居然不见了,而且还多了这么一段:
<dependencyManagement>
<dependencies>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
看了下项目使用spring-boot相关的类没有报红,而且运行了一下项目居然可以正常运行,很是疑惑!没有<parent>标签,父类spring-boot的依赖肯定是没有引进来的啊! 那为啥项目能正常运行呢! 联想到上面<dependencyManagement>标签中恰好有spring-boot和cloud的依赖,但是<dependencyManagement>不是为了方便版本号的统一管理,在父项目pom中定义,子项目中引用的时候就不用引入版本号的作用吗。
印象中就是这样用的啊!????
再仔细看了下此处dependencyManagement 下面dependency标签下,不光有坐标gav 还多了两个从来没有看到过的属性<scope>import</scope> 和<type>pom</type> 。难道端倪就在此处?顺着这个思路百度了一下dependencyManagement 和<scope>import</scope> 关键字,果然发现了很多记录一 一查看后明白了原来是为了解决maven pom 单继承的问题, Maven的继承和java的继承一样,是无法实现多重继承的。像spring这种大型的项目,分为很多个功能模块,如果按照单继承的方式,项目<parent>标签引用的父项目中的<dependencyManagement>标签下内容必定长得无法无天,这样维护起来必定很难受。那为啥不用到哪个模块我就引入哪个模块的<dependencyManagement>呢! 何必非要使用继承呢!所以有了 下面这个的用法:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencyManagement>
翻译一下就是:当前pom文件同时继承 spring-cloud-dependencies 和spring-boot-dependencies
注意:此处 <dependencyManagement>不是版本管理,而是导入多个父模块
这样的用法必须在当前pom中使用<dependencyManagement> </dependencyManagement>标签,并且添加上 <type>pom</type>和<scope>import</scope>标签