作用
统一多个maven module的依赖的版本号
文件目录
形式一
将多个maven module分开放:
- total project
- parent module
- second level one
- second level two
- third level
就是说多个maven 的项目我们就随便放,在pom.xml
里面我们需要做以下修改:
<parent>
<artifactId>parent-module</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../parent-module/pom.xml</relativePath>
</parent>
有个parent
标签,表示我们的父maven是parent-module
,relativePath
就是父项目的pom.xml文件的相对路径
如果有了relativePath
,那么就会在local repo 和remote repo之前先去搜寻这个relativePath
,那么我们就不需要先install了
形式二
将多个maven module按照父子关系放:
- total project
- parent module
- second level one
- third level
- second level two
- second level one
- parent module
就是说将子项目放到父项目里面
这样子我们不需要relativePath
了。
实现
直接继承
在父项目中,我们有
<dependencies>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
</dependency>
</dependencies>
那么子项目会完全继承这些依赖
如果我们不想给所有的子项目都继承父项目的所有依赖,我们不要直接写dependencies
标签
显式继承
我们可以在dependencies
外添加dependencyManagement
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.9</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
</dependencies>
</dependencyManagement>
在dependencyManagement
里面的依赖,子项目不会直接继承,只有在子项目添加这些依赖的时候,才会继承和父项目相同版本的依赖:
<!--子项目-->
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
</dependencies>
这个子项目就会添加5.0.0Alpha2的netty-all,且没有dubbo
在dependencyManagement
外面的dependencies
仍然会无条件继承
properties
一个标签,当然类似于xxx.properties这种文件
我们可以设置一些属性,然后通过${属性名}
的方式去使用
比如我们设置version的时候,可以在properties标签中统一设置
<properties>
<spring-version>5.3.0</spring-version>
<dubbo-version>2.6.9</dubbo-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>${dubbo-version}</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
</dependencies>
</dependencyManagement>
这个属性名当然随便取
版本冲突
如果我们有一个module1
他有两个依赖dep1
和dep2
其中dep1
有依赖dep2
,而且需要是很苛刻的version。
这时如果我们指定了不符合要求的version的dep2
,那么这个dep1
只能使用我们指定的不符合要求的dep2
了,然后就会出错
我们可以使用mvn dependency:tree
来检查我们的依赖问题
依赖机制(dependency mechanism)
maven为了不让我们手动的添加层级依赖,他会自动按照传递关系去添加其他的jar包