maven隐式依赖引起的包冲突

时间:2022-05-16 20:01:34

包冲突

  1. 使用maven管理项目时可能会遇到包冲突的情况比如:log4j-over-slf4j.jar 和 slf4j-log4j12.jar这两个包同时一起运行时就会有问题。
  2. 这种冲突可能是显式依赖导致,也可能是隐式依赖导致。
    • 显式依赖,直接可以从pom.xml文件的<dependency>中看到两个冲突包的引用。
    • 隐式依赖,在pom.xml的<dependency>无法看到冲突的包,而是由<dependency>引入的包间接引入的。

解决

  1. 先确认哪些依赖间接引入了包。使用mvn dependency:tree查看整个项目的依赖树,这里能看到所有的依赖,包括间接依赖。

    结果类似如下:
[INFO] +- junit:junit:jar:4.12:test
[INFO] |  \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] +- org.apache.storm:storm-core:jar:1.0.2:provided
[INFO] |  +- com.esotericsoftware:kryo:jar:3.0.3:compile
[INFO] |  |  \- com.esotericsoftware:minlog:jar:1.3.0:compile
[INFO] |  +- org.clojure:clojure:jar:1.7.0:provided
[INFO] |  +- com.lmax:disruptor:jar:3.3.2:provided
[INFO] |  +- org.apache.logging.log4j:log4j-api:jar:2.1:provided
[INFO] |  +- org.apache.logging.log4j:log4j-core:jar:2.1:provided
[INFO] |  +- org.apache.logging.log4j:log4j-slf4j-impl:jar:2.1:provided
[INFO] |  +- org.slf4j:log4j-over-slf4j:jar:1.6.6:provided
[INFO] |  +- javax.servlet:servlet-api:jar:2.5:provided
[INFO] |  \- org.slf4j:slf4j-api:jar:1.7.7:compile
[INFO] +- com.aaa.khala:aaa-khala-insight-sdk-transfer-api:jar:1.0.0-SNAPSHOT:compile
[INFO] |  \- com.aaa.khala:aaa-khala-common:jar:1.0.0-SNAPSHOT:compile
[INFO] |     +- javax.mail:javax.mail-api:jar:1.5.5:compile
[INFO] |     +- cglib:cglib:jar:2.2.2:compile
[INFO] |     +- org.aspectj:aspectjrt:jar:1.7.4:compile
[INFO] |     +- org.aspectj:aspectjweaver:jar:1.7.4:runtime
[INFO] |     +- org.javassist:javassist:jar:3.20.0-GA:compile
[INFO] |     +- log4j:log4j:jar:1.2.17:compile
[INFO] |     +- org.slf4j:slf4j-log4j12:jar:1.7.7:compile
[INFO] |     +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |     +- jaxen:jaxen:jar:1.1.6:compile
[INFO] |     +- commons-collections:commons-collections:jar:3.2.1:compile
[INFO] |     +- commons-codec:commons-codec:jar:1.9:compile
[INFO] |     +- commons-beanutils:commons-beanutils:jar:1.9.2:compile
[INFO] |     +- org.apache.commons:commons-compress:jar:1.6:compile
[INFO] |     |  \- org.tukaani:xz:jar:1.4:compile
  1. 查到冲突包对应的依赖,在pom.xml的<dependency>中配置排除,就不会引入该包了,例如:
<dependency>
    <groupId>com.aaa.khala</groupId>
    <artifactId>aaa-khala-insight-sdk-transfer-api</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
    </exclusions>
</dependency>