Maven 的聚合(多模块)和 Parent 继承

2017年06月26日 21:16:57 

Maven 的聚合(多模块)和 Parent 继承 - 偶尔记一下 - CSDN博客 https://blog.csdn.net/isea533/article/details/73744497

实际上在 Maven 中聚合(多模块)和继承是两回事,两者不存在直接联系。

pom文档地址:https://maven.apache.org/pom.html
Maven 完全参考:http://books.sonatype.com/mvnref-book/reference/index.html
继承

继承是 Maven 中很强大的一种功能,继承可以使得子POM可以获得 parent 中的各项配置,可以对子pom进行统一的配置和依赖管理。父POM中的大多数元素都能被子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,只需要像下面这样写。

<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元素不是必须的,指定后会优先从指定的位置查找父pom。

聚合(或多模块)

具有模块的项目被称为多模块或聚合项目。模块是此POM列出并作为一组执行的项目。通过一个pom打包的项目可以将它们列为模块来聚合成一组项目进行构建,这些模块名是这些项目的相对目录。

<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>

  

在列出模块时,不需要自己考虑模块间依赖关系,即POM给出的模块排序并不重要。Maven将对模块进行拓扑排序,使得依赖关系始终在依赖模块之前构建。

聚合 VS 父POM

虽然聚合通常伴随着父POM的继承关系,但是这两者不是必须同时存在的,从上面两者的介绍可以看出来,这两者的都有不同的作用,他们的作用不依赖于另一个的配置。

父POM是为了抽取统一的配置信息和依赖版本控制,方便子POM直接引用,简化子POM的配置。聚合(多模块)则是为了方便一组项目进行统一的操作而作为一个大的整体,所以要真正根据这两者不同的作用来使用,不必为了聚合而继承同一个父POM,也不比为了继承父POM而设计成多模块。

原文地址:https://www.cnblogs.com/rsapaper/p/10075283.html