环境: MacBook Pro 15 jdk8 IntelliJ IDEA

引子 对于maven多模块项目,自然会想到每个模块都有自己的pom文件,每个模块都可以在自己的pom中定义自己需要的dependency;很容易想到,多个pom文件中的dependency难免会有重复的(两个模块都依赖同一个dependency很常见),而且每个dependency都有version需要管理,也可能出现冲突不一致等配置问题。 父子模块间单纯的继承关系也有问题,父模块中如果配置很多dependency,继承到不同的子模块中可能会冗余(因为不同模块可能分开部署,冗余无用的jar,怎么能忍!!!)。 如何充分利用模块之间的关系,而又清晰、方便管理不同模块中的dependency?

为解决引子中的问题:maven引入了几个标签(设计开发框架的人都是人精)

  1. parent:模块间根据这个标签进行继承关系。
  2. dependency:管理依赖jar,父模块(parent)中dependency默认,继承到子模块中。
  3. dependencyManagement:统一管理dependency中的version,而且默认不继承;但是管理子模块中相同dependency的version(即子模块,配置相同的dependency不用显示配置version)。

研究问题1-4:maven构建多模块项目,模块间的依赖关系; >1. 子模块可以用parent继承父模块,dependencies中的是每个dependency也自动继承? >2. 父模块使用dependencyManagement管理dependencies中的dependency的version,即当子模块中引用重复(父模块已经引入)的dependency时,可以不用带version控制?方便版本管理?。 >3. dependencyManagement中管理的dependencies中的dependency是否也可以自动继承? >4. 继承是否有传递性?即子模块Sa继承自父模块P,孙子模块Sb继承自子模块Sa,则Sb是否会自动继承P中的dependency?dependencyManagement管理的version又是啥情况?

搞明白上边的几个问题,先理解一个2个标签下dependency的状态: 1. dependencyManagement标签:没有特别标注(specified)情况下,子模块默认继承的dependency的信息(information)是父模块dependencyManagement下管理的,包括版本-version和值-values。 2. dependencies标签:管理依赖(dependency)的列表(list)。 参考官网-maven.apache.org-3.0.3-maven-model

Element

Type

Description

dependencyManagement

DependencyManagement

Default dependency information for projects that inherit from this one. The dependencies in this section are not immediately resolved. Instead, when a POM derived from this one declares a dependency described by a matching groupId and artifactId, the version and other values from this section are used for that dependency if they were not already specified.

ependencies/dependency*

List(Dependency)

(Many) This element describes all of the dependencies associated with a project. These dependencies are used to construct a classpath for your project during the build process. They are automatically downloaded from the repositories defined in this project. See the dependency mechanism for more information.

栗子说明: 问题1答案:父模块中dependencies内的dependency可以自动继承到子模块中;但是dependencyManagement标签下的dependencies中的dependency不会自动继承到子模块,子模块需要显示引用dependency的groupId和artifactId,version则可选(建议放在父模块中管理)。

问题2答案:是的,父模块dependencyManagement主要管理dependencies中的dependency的信息(包括version和values)。

问题3答案:不是,父模块dependencyManagement管理的dependencies中的dependency不会在子模块默认继承,子模块继承,需要显示定义dependencies中的具体dependency的groupId和artifactId(version可选,建议在父模块管理)。这样父模块既可以统一管理dependency的版本,避免jar包冲突;子模块也可以自由选择,不会冗余加载子模块用不到的jar。

参考:

官网-maven.apache.org-3.0.3-maven-model

maven多个子项目、父项目之间的引用问题

Maven多模块项目管理小结