规则来源
maven官网中的 依赖机制 一文详细解析了如何解决依赖冲突,确定最终的依赖版本。
规则摘要
- Dependency mediation - this determines what version of an artifact will be chosen when multiple versions are encountered as dependencies. Maven picks the "nearest definition". That is, it uses the version of the closest dependency to your project in the tree of dependencies. You can always guarantee a version by declaring it explicitly in your project's POM. Note that if two dependency versions are at the same depth in the dependency tree, the first declaration wins.
- Dependency management - this allows project authors to directly specify the versions of artifacts to be used when they are encountered in transitive dependencies or in dependencies where no version has been specified.
规则总结
声明
一般的pom文件会有如下的结构,本节在阐述规则优先级时,<dependencies>指的是与<dependencyManagement>同一级别的<dependencies>标签,而不是<dependencyManagement>内部嵌套的<dependencies>标签
<project>
<!-- 本节阐述规则优先级时,指的是这个<dependencies>标签 -->
<dependencies>
....
</dependencies>
<dependencyManagement>
<!-- 不是这个<dependencies>标签 -->
<dependencies>
....
</dependencies>
</dependencyManagement>
</project>
依赖的版本号根据以下顺序确定
- 当前pom文件的 <dependencies> 中的声明
因此手动解决版本冲突的最简单的方式就是在当前pom文件中明确声明一下 - <dependencyManagement>
2.1 <dependencyManagement> 中声明的版本号会优先于<dependencies>中的传递引入的<dependencies>。注意,仅优先于<dependencies>的传递引入(transitive),当前文件中<dependencies>声明的版本依旧是第一优先级,见规则1。
dependency management takes precedence over dependency mediation for transitive dependencies
2.2. <dependencyManagement>来源
<dependencyManagement>引入的方式有多种
- 在当前文件中声明
- 在parent中声明,可以是多层parent
- 在<dependencyManagement>中import pom
这些方式引入的依赖声明中也会产生冲突,解决方式是nearest definition和the first declaration wins,如规则摘要一节中所述
- <dependencies>
3.1 优先级最低的是<dependencies>中通过传递引入的依赖
3.2 传递引入的依赖中也会产生冲突,解决方式是nearest definition和the first declaration wins,如规则摘要一节中所述
附
使用如下命令可以合并dependencyManagement,并输出,用于追踪生效版本来源于哪个pom文件的<dependencyManagement>的定义。
mvn help:effective-pom -Dverbose=true -Doutput=effective-pom.xml