1.dependency簡(jiǎn)介
dependency 元素用于定義對(duì)其他項(xiàng)目的依賴(lài)關(guān)系,其中,常見(jiàn)的子元素有:groupId , artifactId , version , type , scope , systemPath , optional , classifier , exclusions 等。其中,絕大部分元素,我們前面都有介紹過(guò),這里就不一一贅述了。我們這里簡(jiǎn)要介紹一下 version 元素的多種表示方式。
version 有如下表示方式
- 1.0 : 非硬性要求,只是一個(gè)建議
- [1.0] : 硬性要求,版本必須為1.0
- (,1.0] : x <= 1.0
- [1.2,1.3] : 1.2 <= x <= 1.3
- [1.0,2.0) :1.0 <= x < 2.0
- [1.5,) :x >= 1.5
- (,1.0],[1.2,) : x <= 1.0 or x >= 1.2,多個(gè)集合以逗號(hào)分隔
- (,1.1),(1.1,) : 排除1.1版本號(hào)的其他版本
2.dependencies和dependencyManagement的區(qū)別概述
在 pom.xml 文件中,我們可以看到,dependencies 是 dependency 的父元素,而 dependencyManagement 又是 dependencies 的父元素,而 dependencies 元素的使用情況又分為兩種,一種,dependencies 元素外沒(méi)有 dependencyManagement 父元素,另一種,dependencies 元素外還存在 dependencyManagement 父元素。當(dāng)然,兩種使用情況可以在同一 pom.xml 文件中共存,因?yàn)槎叩淖饔貌煌?/p>
我們知道 dependency 元素是用來(lái)定義本項(xiàng)目對(duì)其他項(xiàng)目的依賴(lài)關(guān)系的。那么, dependencies 和 dependencyManagement 中 dependency 的作用又有什么不同呢?從宏觀上講,dependencies 中的 dependency 元素下聲明的依賴(lài)會(huì)被引入當(dāng)前項(xiàng)目,而且在子項(xiàng)目中即使不寫(xiě)該依賴(lài)項(xiàng),依舊會(huì)從父項(xiàng)目中繼承該依賴(lài)項(xiàng)(全部繼承),而 dependencyManagement 中的 dependencies 中的 dependency 元素下聲明的依賴(lài)不會(huì)被引入當(dāng)前項(xiàng)目,它僅僅是一個(gè)聲明,如果在子項(xiàng)目中不寫(xiě)該依賴(lài)項(xiàng),則不會(huì)從父項(xiàng)目中繼承該依賴(lài)項(xiàng),如果子項(xiàng)目真的需要引入該依賴(lài),則在聲明的時(shí)候,可以不用指定具體版本號(hào),會(huì)自動(dòng)繼承父項(xiàng)目 dependencyManagement 中聲明的版本號(hào),從而實(shí)現(xiàn)了對(duì)依賴(lài)版本的統(tǒng)一管理。當(dāng)然,如果子項(xiàng)目需要使用不同于父項(xiàng)目中聲明的版本號(hào),則需要在聲明時(shí)指定版本號(hào)。
3.dependencyManagement小結(jié)
通過(guò) dependencyManagement 元素,可以將項(xiàng)目的依賴(lài)關(guān)系細(xì)節(jié)收歸一處,方便管理和升級(jí)。然而,我們?cè)谙硎?dependencyManagement 元素帶來(lái)的巨大便利的同時(shí),需要特別注意的是,通過(guò)依賴(lài)傳遞而被引入的項(xiàng)目依賴(lài)的版本(version)和有效范圍(scope)都會(huì)受到 dependencyManagement 元素中對(duì)應(yīng)依賴(lài)的控制(如果存在對(duì)應(yīng)依賴(lài)的話)。例如:項(xiàng)目A需要依賴(lài)項(xiàng)目B和項(xiàng)目C,項(xiàng)目A的 dependencyManagement 元素中聲明了項(xiàng)目B的版本為1.0,如果此時(shí)項(xiàng)目C也依賴(lài)項(xiàng)目B,而且只有項(xiàng)目B的版本大于等于2.0,項(xiàng)目C才能運(yùn)行。這時(shí)候,項(xiàng)目A中引入對(duì)項(xiàng)目B的依賴(lài),其版本按照 dependencyManagement 中的聲明為1.0版本,這時(shí)候就會(huì)導(dǎo)致項(xiàng)目不能正常運(yùn)行。這一點(diǎn),需要特別注意。