Maven實戰--- dependencies與dependencyManagement的區別
阿新 • • 發佈:2018-12-16
一句話解釋
- 專案中多個模組間公共依賴的版本號、scope的控制
業務場景
- 一個專案有很多模組,每個模組都會用到一些公共的依賴
- 這些公共的依賴若交由各個模組獨自管理,若每個模組同一個依賴的版本號不一致,會給專案的整
- 打包和開發測試環境下對同一 jar 包不同版本號的處理可能不一致,造成執行時和測試時結果不一致
- 專案升級時,會造成修改版本號時遍地開花的問題
- 該標籤通常適用於多模組環境下定義一個top module來專門管理公共依賴的情況下
專案中依賴包版本號判斷途徑
- 若 dependencies 裡的 dependency 自己沒有宣告 version 元素,那麼maven 就會 到 depenManagement 裡去找有沒有該 artifactId 和 groupId 進行過版本宣告,若存在,則繼承它,若沒有則報錯,
- 若 dependencies 中的 dependency 聲明瞭version,則 dependencyManagement 中的宣告無效
單一模組情況下 pom.xml
//只是對版本號進行管理,不會實際引入jar <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> //jar 包身份限定 <artifactId>spring-core</artifactId> <version>3.2.7</version> //版本號的宣告 </dependency> </dependencies> </dependencyManagement> //會實際下載jar包 <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> //不宣告version 標籤,則會繼承 </dependency> </dependencies>
多模組情況: parent-module 頂層模組,son1-module 和 son2-module 並列繼承 parent-module
parent-module 中 pom.xml <properties> // 集中在properties 標籤中定義所有 依賴的版本號 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <org.eclipse.persistence.jpa.version>1.2.6</org.eclipse.persistence.jpa.version> <developer.organization>xxx</developer.organization> <javaee-api.version>1.8</javaee-api.version> </properties> <dependencyManagement> //定義公共依賴的版本號 <dependencies> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa</artifactId> <version>${org.eclipse.persistence.jpa.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>${javaee-api.version}</version> </dependency> </dependencies> </dependencyManagement>
son-module1 中 的 pom.xml
<!--繼承父類-->
<parent>
<artifactId>parent-module</artifactId> //宣告父類的身份資訊
<groupId>com.ppd</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-module/pom.xml</relativePath> //宣告父類的pom 檔案路徑
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>son-module</artifactId>
<packaging>ejb</packaging>
<!--依賴關係-->
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId> //繼承父類
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId> //繼承父類
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId> //繼承父類
<scope>provided</scope>
</dependency>
</dependencies>
與 dependencies 標籤下 dependency 的區別
- 所有宣告在d ependencies 裡的依賴都會自動引入,並預設被所有的子專案繼承
- dependencies 即使在子專案中不寫該依賴項,那麼子專案仍然會從父專案中繼承該依賴項(全部繼承)
- dependencyManagement 只是宣告依賴的版本號,該依賴不會引入,因此子專案需要顯示宣告所需要引入的依賴,若不宣告則不引入
- 子專案聲明瞭依賴且未宣告版本號和scope,則會繼承父專案的版本號和scope,否則覆蓋
作者:HelloTrident 連結:https://www.jianshu.com/p/ee15cda51d9d 來源:簡書 簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。