即使是長(zhǎng)期從事 maven 工作的開發(fā)人員也不能完全掌握聚合(多模塊)和 parent 繼承的關(guān)系,在使用多模塊時(shí),子模塊總要指定聚合的 pom 為 <parent>
。由于在大多數(shù)示例中都是這么寫的,所以很難讓人搞懂這兩者的具體作用和關(guān)系。
實(shí)際上在 maven 中聚合(多模塊)和繼承是兩回事,兩者不存在直接聯(lián)系。
pom文檔地址:https://maven.apache.org/pom.html
Maven 完全參考:http://books.sonatype.com/mvnref-book/reference/index.html
繼承
繼承是 maven 中很強(qiáng)大的一種功能,繼承可以使得子pom可以獲得 parent 中的各項(xiàng)配置,可以對(duì)子pom進(jìn)行統(tǒng)一的配置和依賴管理。父pom中的大多數(shù)元素都能被子pom繼承,這些元素包含:
- groupid
- version
- description
- url
- inceptionyear
- organization
- licenses
- developers
- contributors
- mailinglists
- scm
- issuemanagement
- cimanagement
- properties
- dependencymanagement
- dependencies
- repositories
- pluginrepositories
- build
- plugin executions with matching ids
- plugin configuration
- etc.
- reporting
- profiles
注意下面的元素,這些都是不能被繼承的。
- artifactid
- name
- prerequisites
想要添加 parent,只需要像下面這樣寫。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<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 https: //maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion> 4.0 . 0 </modelversion> <parent> <groupid>org.codehaus.mojo</groupid> <artifactid>my-parent</artifactid> <version> 2.0 </version> <relativepath>../my-parent</relativepath> </parent> <artifactid>my-project</artifactid> </project> |
其中relativepath
元素不是必須的,指定后會(huì)優(yōu)先從指定的位置查找父pom。
聚合(或多模塊)
具有模塊的項(xiàng)目被稱為多模塊或聚合項(xiàng)目。模塊是此pom列出并作為一組執(zhí)行的項(xiàng)目。通過一個(gè)pom
打包的項(xiàng)目可以將它們列為模塊來聚合成一組項(xiàng)目進(jìn)行構(gòu)建,這些模塊名是這些項(xiàng)目的相對(duì)目錄。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<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 https: //maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion> 4.0 . 0 </modelversion> <groupid>org.codehaus.mojo</groupid> <artifactid>my-parent</artifactid> <version> 2.0 </version> <packaging>pom</packaging> <modules> <module>my-project</module> <module>another-project</module> </modules> </project> |
在列出模塊時(shí),不需要自己考慮模塊間依賴關(guān)系,即pom給出的模塊排序并不重要。maven將對(duì)模塊進(jìn)行拓?fù)渑判颍沟靡蕾囮P(guān)系始終在依賴模塊之前構(gòu)建。
聚合 vs 父pom
雖然聚合通常伴隨著父pom的繼承關(guān)系,但是這兩者不是必須同時(shí)存在的,從上面兩者的介紹可以看出來,這兩者的都有不同的作用,他們的作用不依賴于另一個(gè)的配置。
父pom是為了抽取統(tǒng)一的配置信息和依賴版本控制,方便子pom直接引用,簡(jiǎn)化子pom的配置。聚合(多模塊)則是為了方便一組項(xiàng)目進(jìn)行統(tǒng)一的操作而作為一個(gè)大的整體,所以要真正根據(jù)這兩者不同的作用來使用,不必為了聚合而繼承同一個(gè)父pom,也不比為了繼承父pom而設(shè)計(jì)成多模塊。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)服務(wù)器之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
原文鏈接:https://blog.csdn.net/isea533/article/details/73744497