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。
依賴範圍有一種是import、是隻有在dependencyManagement元素下才有效果的、使用該範圍的依賴通常指向一個POM、作用是将目标POM中的dependencyManagement配置導入并合并到目前POM的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>