DependencyManagement
引入
在多模块的项目中,如果在父pom中使用dependencies来管理依赖,那么在子模块中,无论是否需要父pom中的依赖,都会强制的继承过来,这样就不太有很好了。可以简单的理解为Java中的implements 无论是否需要,都要实现父类中的所有依赖的。而dependencyManagement不是这样的,只是提供了子模块中可能用到的一些依赖,不会强制子模块引入依赖,而这个就像是Java中的abstract Class,具体要不要实现父类中的依赖,完全由子模块来决定。
实例
父pom
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactid>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactid>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
</dependencyManagement>
子模块Pom
<dependency>
<groupId>junit</groupId>
<artifactid>junit</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactid>log4j</artifactId>
</dependency>
这样一来,就变得容易管理,使得各个子模块中的依赖的版本&scode是一样的,不存在出现重复依赖。|== 关键的地方是在父POM中的dependencyManagement标签中配置的依赖是不会主动引入到子项目中的、也就是说虽然在父POM中的dependencyManagement定义了junit的依赖、假如子类中没有关于junit的、那么子类就没有junit依赖的引入、并且假如子项目不想使用4.1版本的junit、还可以指定自己想要使用的junit版本、这样就完全覆盖了父POM中关于junit的定义、也就是说父POM中的junit定义与他无关。
更进一步
我们知道Maven的继承和Java的继承一样,是无法实现多重继承的,如果10个、20个甚至更多模块继承自同一个模块,那么按照我们之前的做法,这个父模块的dependencyManagement会包含大量的依赖。如果你想把这些依赖分类以更清晰的管理,那就不可能了,import scope依赖能解决这个问题。你可以把dependencyManagement放到单独的专门用来管理依赖的POM中,然后在需要使用依赖的模块中通过import scope依赖,就可以引入dependencyManagement。
实例
A pom
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.volshell.sample</groupId>
<artifactId>A</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactid>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactid>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
B pom
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.volshell.sample</groupId>
<artifactid>A</artifactId>
<version>1.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency>
<groupId>junit</groupId>
<artifactid>junit</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactid>log4j</artifactId>
</dependency>