在解决库版本冲突(主要就是jar包版本冲突)之前,首先要明白Maven对于使用相同库的哪个版本,它是通过什么策略决定的。主要是两个策略:
- nearest-wins 路径最近的获胜
- the first declaration wins 最先声明的获胜
下面通过两个例子来说明:
mvn dependency:tree -Dverbose -Dincludes=commons-collections:commons-collections -f D:\pom.xml
[INFO] [dependency:tree]
[INFO] org.apache.maven.plugins:maven-dependency-plugin:maven-plugin:2.0-alpha-5-SNAPSHOT
[INFO] +- org.apache.maven.reporting:maven-reporting-impl:jar:2.0.4:compile
[INFO] | \- commons-validator:commons-validator:jar:1.2.0:compile
[INFO] | \- commons-digester:commons-digester:jar:1.6:compile
[INFO] | \- (commons-collections:commons-collections:jar:2.1:compile - omitted for conflict with 2.0)
[INFO] \- org.apache.maven.doxia:doxia-site-renderer:jar:1.0-alpha-8:compile
[INFO] \- org.codehaus.plexus:plexus-velocity:jar:1.1.3:compile
[INFO] \- commons-collections:commons-collections:jar:2.0:compile
可以看到commons-collections:jar:2.0只用3层就可以找到,而commons-collections:jar:2.1需要经过4层才能打到,因此就选择使用最近的那个,也就是commons-collections:jar:2.0
官方文档中的解释:
if two dependency versions are at the same depth in the dependency tree, the first declaration wins.
mvn dependency:tree -Dverbose -Dincludes=log4j:log4j -f D:\pom.xml
[INFO] [dependency:tree {execution: default-cli}]
[INFO] com.openboxes.renderingservice:common:jar:1.0
[INFO] +- org.springframework:spring:jar:2.0.4:compile
[INFO] | \- commons-logging:commons-logging:jar:1.1:compile
[INFO] | \- log4j:log4j:jar:1.2.12:compile
[INFO] \- it.mycompany.portal:server:jar:1.5-SNAPSHOT:compile
[INFO] \- org.slf4j:slf4j-log4j12:jar:1.1.0:compile
[INFO] \- (log4j:log4j:jar:1.2.13:compile - omitted for conflict with 1.2.12)
log4j:jar:1.2.12和log4j:jar:1.2.13都只用3层就可以找到,但log4j:jar:1.2.12先出现的,因此使用log4j:jar:1.2.12
对于1,有以下3种解决方法:
a、将commons-collections:jar:2.1直接在
commons-collections
commons-collections
2.1
org.apache.maven.reporting
maven-reporting-impl
2.0.4
org.apache.maven.doxia
doxia-site-renderer
1.0-alpha-8
b、将commons-collections:jar:2.1直接在
commons-collections
commons-collections
2.1
org.apache.maven.reporting
maven-reporting-impl
2.0.4
org.apache.maven.doxia
doxia-site-renderer
1.0-alpha-8
c、使用
org.apache.maven.reporting
maven-reporting-impl
2.0.4
org.apache.maven.doxia
doxia-site-renderer
1.0-alpha-8
commons-collections
commons-collections
对于2,除了能使用对于1的方法解决外,还可以使用如下方法:
如果这两个不同版本库的根路径不相同,则可以调整这2个根路径对应的库的声明在pom.xml中的顺序。
调整前:
org.springframework
spring
2.0.4
it.mycompany.portal
server
1.5-SNAPSHOT:
调整后:
it.mycompany.portal
server
1.5-SNAPSHOT:
org.springframework
spring
2.0.4
参考文档
Introduction to the Dependency Mechanism
http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html
Resolving conflicts using the dependency tree
http://maven.apache.org/plugins/maven-dependency-plugin/examples/resolving-conflicts-using-the-dependency-tree.html
Interpreting “omitted for conflict” in maven 2 dependency tree
https://stackoverflow.com/questions/7742312/interpreting-omitted-for-conflict-in-maven-2-dependency-tree