Maven系列五:多模块项目中的聚合和继承

来源:互联网 发布:四轮定位电脑数据图解 编辑:程序博客网 时间:2024/06/05 07:28

一、Maven项目的聚合

现在项目越来越复杂,一般情况下,一个项目包括多个模块。

假设有个orchid项目,包括两个模块:orchid-server和orchid-support。

它们在文件系统的目录结构如下所示

orchid--pom.xml--orchid-support--src--pom.xml--orchid-server--src--pom.xml

那么如何把它们作为一个多模块的maven项目配置呢?

orchid/pom.xml的配置如下:

<modelVersion>4.0.0</modelVersion><groupId>com.stear.orchid</groupId><artifactId>orchid</artifactId><version>0.1</version><packaging>pom</packaging><name>orchid</name><description>The orchid project of stear</description><url>http://orchid.stear.com</url><modules><module>orchid-server</module><module>orchid-support</module>  </modules>

这个pom.xml的配置关键在两点:(1)packaging类型为pom;(2)<modules>模块的引入。

<module>orchid-server</module>

表示在当前目录(也就是上面pom.xml所在目录)包括一个文件夹orchid-server。如果orchid-server和orchid在同一目录的话,那么配置应该是

<module>../orchid-server</module>

二、Maven项目的继承

在上面的例子中只有聚合,也就是说orchid-support和orchid-server是不知道有个总项目或者说父项目存在的,因为我们没有在orchid-support/pom.xml和orchid-server/pom.xml中加入任何东西。那么orchid-support和orchid-server也是不能从orchid项目继承任何东西的。如果需要继承的话,那么需要在子项目的配置中加入<parent>配置:

orchid-support:

<modelVersion>4.0.0</modelVersion><parent><groupId>com.stear.orchid</groupId><artifactId>orchid</artifactId><version>1.0-SNAPSHOT</version></parent><artifactId>orchid-support</artifactId>


orchid-server:

<modelVersion>4.0.0</modelVersion><parent><groupId>com.stear.orchid</groupId><artifactId>orchid</artifactId><version>1.0-SNAPSHOT</version></parent><artifactId>orchid-server</artifactId>
上面两个配置在<parent>中都忽略了<relativePath>标签,<relativePath>的默认值是../pom.xml,也就是从父目录中寻找pom.xml。

如果你的父项目在其他地方,那么要手工加入改配置

<parent><groupId>com.stear.orchid</groupId><artifactId>orchid</artifactId><version>1.0-SNAPSHOT</version><relativePath>parent project orchid directory/pom.xml</relativePath></parent>

这样子项目可以从父项目中继承元素。可继承的元素包括:

groupId

version

description

organization

inceptionYear

url

developers

contributors

distributionManagement

issueManagement

ciManagement

scm

mailingLists

properties

dependencies

dependencyManagement

repositories

build

reporting

三、聚合和继承的关系

聚合和继承本质上没什么关系。聚合是为了快速构建,只要在总项目中执行命令就会自动构建包含的某块项目。继承是为了消除重复配置,各个子项目可以继承父项目中的配置

对于聚合的总项目来说,它知道有哪些项目被聚合在一起,而各个模块对总的项目是一无所知的。

对于继承的父项目来说,它不知道哪些项目会继承它,但是子项目明确指明了父项目。

通常来说,父项目和总项目是一个项目。也是为了结构的清晰可见。