一.dependencyManagement
dependencyManagement用在父pom中
用来统一管理项目的版本号, 确保各个子项目的依赖和版本一致
子项目可以不用声明版本号, 但是一定要显示声明引用父pom的jar
不然不会默认导入父pom的所有依赖
父pom
<dependencyManagement>
<dependencies>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
</dependencies>
</dependencyManagement>
子pom
<!-- 不用显示声明版本, 可以声明或者其他版本-->
<dependencies>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
二.optional
自己模块的依赖不想让引用我模块的人用
子pom
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.8</version>
<optional>true</optional>
</dependency>
引用子pom的模块
<!-- 这里引用子pom, 默认会把子pom依赖全部加载-->
<!-- 但是由于子pom中optional为true, 就不会把子pom的hutool依赖加载-->
<dependencies>
<dependency>
<groupId>com.xxx</groupId>
<artifactId>xxx-child</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
三.scope的import
存在问题: 标题一中的dependencyManagement很好的解决了子模块依赖版本杂乱无章, 由父pom模块统一定义依赖版本, 但是这样一来父pom文件中dependencyManagement依赖的版本定义过多就显得过于臃肿, 所以可以把这个父pom进行拆分, 在常规方式中子模块要引用父模块是如下这样引用
<parent>
<groupId>com.xxx</groupId>
<artifactId>aming-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
但是我还想继承其他的父pom依赖怎么办 maven 低版本只支持单继承, maven2.9以上版本支持了众望所归的多继承 如何使用呢
<!-- 如下方式 子模块可以引入多个父pom依赖-->
<parent>
<groupId>com.xxx</groupId>
<artifactId>aming-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
...
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.xxx</groupId>
<artifactId>aming-parent2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<type>pom</type> <!-- 固定搭配-->
<scope>import</scope> <!-- 固定搭配-->
</dependency>
</dependencies>
</dependencyManagement>
这种使用方式和使用parent标签达到的效果是有一点区别的
如果在parent2的pom中显示用dependencies定义依赖(不建议这样做) 按道理子模块会默认引入依赖, 但是通过scope的import标签引入的父模块则不会自动引入依赖, 只会对parent2的dependencyManagement声明依赖的版本感冒
如何单独引入其他父pom的dependencies定义的依赖呢 也是可以的
和声明其他依赖一样在子模块中引入需要引入pom类型的父模块
<dependencies>
<dependency>
<groupId>com.xxx</groupId>
<artifactId>aming-parent2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<type>pom</type>
</dependency>
</dependencies>
这样一来就可以显示使用父pom的依赖和由父pom统一版本 鱼与熊掌可兼得啊 哈哈哈