maven 的继承,能让我们从父pom中继承到一些配置。我们可以将一些通用的配置放在父pom中,来减少配置项。
实例
如图所示,有一个 inherit 项目,并且引入了一个依赖
假如我想继承这个pom,该怎么做呢?
只需声明 parent 即可。注意,version必须填写
<parent>
<groupId>com.wqlm</groupId>
<artifactId>inherit</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../inherit</relativePath>
</parent>
relativePath
relativePath 的值是父项目的相对于当前pom的路径
如上图,inherit 和 inherit-util 在同一个目录下,所以inherit-util的 relativePath 为 …/inherit
注意 relativePath 的值是父项目的相对于当前pom的路径,而不是artifactId。如下图
Maven首先在当前构建项目的环境中查找父pom,然后项目所在的文件系统查找,然后是本地存储库,最后是远程repo。
比如你将 inherit 安装到本地仓库中之后,子项目可以不写路径
能被继承的元素
子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
packaging 的类型
packaging 默认值为 jar,也就是将项目打包成jar包
继承对 packaging 的类型没有要求,如实例所示,父类的 packaging 没写,则说明父类的打包类型为jar,但依然可以被子类继承。
实际使用中,父类一般不会写代码,一般负责通用配置,所以大部分情况下都会把packaging设置为pom