前言
Maven中的dependencyManagement元素提供了一種管理依賴版本號的方式,她用於聲明所依賴的jar包的版本號等信息。當所有子項目再次引入這些jar包時,則無需顯式的定義version屬性。Maven會沿着父子層級向上尋找擁有dependencyManagement 元素的項目,然后繼承它約定的版本號。
使用方法
pom文件中,有兩種途徑判斷jar的版本號。
-
子項目未聲明依賴版本號,則繼承父項目中的。如果dependency標簽未曾聲明version元素,那么maven就會到父項目dependencyManagement標簽里面去找該artifactId和groupId 的版本聲明信息,如果找到了,就繼承它;否則,就會拋出異常,告訴你必須為dependency聲明version屬性。
-
子項目定義的依賴版本號優先級高於父項目的。如果dependency標簽聲明了version屬性,那么無論dependencyManagement中有無對該jar的version聲明,都以dependency里的為准。
在父項目的POM.xml中配置dependencyManagement標簽,定義基本的父依賴。這里僅僅定義一個Junit5的依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wiener</groupId>
<artifactId>springBoot</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
<module>wiener-demo</module>
</modules>
<!--打包方式pom-->
<packaging>pom</packaging>
<properties>
<junit-jupiter.version>5.5.2</junit-jupiter.version>
</properties>
<!-- 版本管理,導入需要的模塊-->
<dependencyManagement>
<dependencies>
<!-- junit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
</build>
</project>
在wiener-demo(pom.xml)中定義Junit5依賴:
//子項目實際引用的jar包
<dependencies>
<!-- junit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
</dependencies>
modules標簽中的模塊就是項目的子模塊,他們都受到父模塊的版本約束,但是需要自己導入子模塊的依賴。dependencyManagement標簽定義項目通用的父依賴,各個依賴的版本號由properties標簽定義,通過${變量名}的形式動態獲取版本號。
例如,在父依賴中junit5依賴的版本號5.5.2就定義在properties標簽中,變量名是junit-jupiter.version,而dependencyManagement標簽通過${junit-jupiter.version}導入版本號;在用到Junit5依賴的子模塊中,只需聲明依賴,無需描述版本信息。
結束語
在頂層pom文件中,通過標簽dependencyManagement定義公共的依賴關系,讓所有的子項目使用依賴項的統一版本,確保應用的各個項目的依賴項和版本一致,保證測試的和發布的是相同的結果。
這樣做的優點是避免在每個子項目里都聲明一個版本號,當想升級或切換到另一個版本時,只需要在頂層父容器里更新,而避免逐個修改子項目;另外如果某個子項目需要另外的一個版本,只需要在子項目聲明version即可。溫馨提示,dependencyManagement標簽中定義的只是依賴的聲明,並不實現引入,因此子項目需要顯式的聲明需要用的依賴。