maven單繼承的問題
阿新 • • 發佈:2021-06-27
title: maven單繼承的問題
tags: [maven]
categories: [工具]
date: 2017/3/13 10:46:25
我們知道Maven的繼承和Java的繼承一樣,是無法實現多重繼承的,如果10個、20個甚至更多模組繼承自同一個模組會有什麼問題呢,有什麼現有的解決方法呢?
單繼承的問題
那麼按照我們之前的做法,這個父模組的dependencyManagement會包含大量的依賴。如果你想把這些依賴分類以更清晰的管理,那就不可能了,import scope依賴能解決這個問題。你可以把dependencyManagement放到單獨的專門用來管理依賴的pom中,然後在需要使用依賴的模組中通過import scope依賴,就可以引入dependencyManagement。例如可以寫這樣一個用於依賴管理的 pom
繼承方式引用
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
import(聚合)方式引用
定義用於依賴的POM
自定義 (base-parent1)
<project> <modelVersion>4.0.0</modelVersion> <groupId>com.test.sample</groupId> <artifactId>base-parent1</artifactId> <packaging>pom</packaging> <version>1.0.0-SNAPSHOT</version> <dependencyManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactid>junit</artifactId> <version>4.8.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactid>log4j</artifactId> <version>1.2.16</version> </dependency> </dependencies> </dependencyManagement> </project>
import 依賴POM
- 注意:import scope只能用在dependencyManagement裡面
<dependencyManagement> <dependencies> <dependency> <groupId>com.test.sample</groupId> <artifactid>base-parent1</artifactId> <version>1.0.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>
這樣,父模組的pom就會非常乾淨,由專門的packaging為pom來管理依賴,也契合的面向物件設計中的單一職責原則。此外,我們還能夠建立多個這樣的依賴管理pom,以更細化的方式管理依賴。這種做法與面向物件設計中使用聚合而非繼承也有點相似的味道。
eg. 應用在SpringBoot中
這樣配置的話,自己的專案裡面就不需要繼承SpringBoot的module了,而可以繼承自己專案的module了。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>