《轉》maven中import scope依賴方式解決單繼承問題的理解
在maven多模組專案中,為了保持模組間依賴的統一,常規做法是在parent model中,使用dependencyManagement預定義所有模組需要用到的dependency(依賴)
<dependencyManagement>
<dependencies>
<!-- Feign是一種宣告式、模板化的HTTP客戶端:以HTTP介面的形式暴露自身服務 -->
<dependency>
<groupId>org.springframework.cloud</groupId >
<artifactId>spring-cloud-starter-feign</artifactId>
<version>${spring-cloud-starter-feign.version}</version>
</dependency>
<!-- 支援面向方面的程式設計即AOP,包括spring-aop和AspectJ -->
<dependency>
<groupId >org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId >
<artifactId>aspectjrt</artifactId>
<version>${aspectjrt.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
然後,子model根據實際需要引入parent中預定義的依賴,
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
好處:
1、依賴統一管理(parent中定義,需要變動dependency版本,只要修改一處即可);
2、程式碼簡潔(子model只需要指定groupId、artifactId即可)
3、dependencyManagement只會影響現有依賴的配置,但不會引入依賴,即子model不會繼承parent中dependencyManagement所有預定義的depandency,只引入需要的依賴即可,簡單說就是“按需引入依賴”或者“按需繼承”;因此,在parent中嚴禁直接使用depandencys預定義依賴,壞處是子model會自動繼承depandencys中所有預定義依賴;
但是,問題也出現了:
單繼承:maven的繼承跟java一樣,單繼承,也就是說子model中只能出現一個parent標籤;
parent模組中,dependencyManagement中預定義太多的依賴,造成pom檔案過長,而且很亂;
如何讓這些依賴可以分類並清晰的管理?
問題解決:import scope依賴
如何使用:
1、maven2.9以上版本
2、將dependency分類,每一類建立單獨的pom檔案
3、在需要使用到這些依賴的子model中,使用dependencyManagement管理依賴,並import scope依賴
3、注意:scope=import只能用在dependencyManagement裡面,且僅用於type=pom的dependency
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<!-- 重要:版本號要和父模組中預定義的spring boot版本號保持一致 -->
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
個人總結
看了幾篇文章,看了這個之後總算知道了這個是什麼意思。
1.一般多模組管理依賴都是在父pom.xml宣告dependencyManagement,然後子模組顯示依賴(無需版本)
dependencyManagement: 專門為了管理模組依賴,不會被直接傳遞到子模組,需要顯示依賴。
父pom.xml不應該定義dependencies,除非是所有模組都需要的,因為這個會直接傳遞給子模組
2.但是如果我們還需要引用其他系統的一些模組,寫很多個dependency顯然太low,如果能直接引用這個系統的父pom.xml就好了
但是maven是單繼承,因此子模組不能再繼承其他系統的parent pom.xml了.
於是就有了scope:import
》只能在dependencyManagement
》type只能是pom.xml(即父pom.xml)
》是宣告在parent pom.xml的dependencyManagement,提供給子模組引用的
作用就相當於把其他系統的父pom.xml的子模組全部引入進來了,
並且子模組在用的時候可以只需要依賴該系統的一部分模組
(例如import spring-parent.pom, 子模組可以只依賴spring-web)