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

2025-05-29 0 95

即使是长期从事 maven 工作的开发人员也不能完全掌握聚合(多模块)和 parent 继承的关系,在使用多模块时,子模块总要指定聚合的 pom 为 <parent>。由于在大多数示例中都是这么写的,所以很难让人搞懂这两者的具体作用和关系。

实际上在 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,只需要像下面这样写。

?

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

聚合(或多模块

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

?

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>

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

聚合 vs 父pom

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

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/isea533/article/details/73744497

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Maven的聚合(多模块)和Parent继承 https://www.kuaiidc.com/110683.html

相关文章

发表评论
暂无评论