有时候,pom会引入同一个jar包的不同版本,但是这些不同版本的jar包会引起冲突。这时候怎么办呢?
我们可以利用maven的dependency tree来帮助我们查看项目的依赖情况。
基础语法如下:
mvn dependency:tree
加上一个“-Dverbose”会显示更详细的信息。
用个栗子来体会一下:
有一天王小谦在试图启动一个部署在tomcat上的web程序时遇到了这样一个错:
......
Caused by: org.springframework.beans.BeanInstantiation: Failed to instantiate [<xxx calss related to cassandra>]: ......
Caused by: java.lang.AbstractMethodError: Reveiver class io.netty.channel.nio.NioEventLoopGroup does not define or inherit an implementation of the resolved method abstract newChild(Ljava/util/concurrent/Executor;[Ljava/lang/Object;) Lio/netty/util/concurrent/EventExecutor; of abstract class io.netty.util.concurrent.MultithreadEventExecutorGroup
这个io.netty.util.concurrent.MultithreadEventExecutorGroup 是在一个叫 netty-common 的jar包里。有可能是因为程序编译的时候被ClassLoader载入的netty-common.jar包并不是Cassandra需要的版本吗?
这时候我们可以用dependency tree来查看一番:
cd <含有pom.xml的文件夹>
mvn dependency:tree -Dverbose -DoutputFile=<自己起个文件名>.txt
“-DoutputFile”可以将输出结果存入一个txt文件中,避免了在控制台看得眼花缭乱的情况(当然如果依赖比较少其实无所谓)。结果的其中一段:
| | | ......
| | +-io.netty:netty-common:jar:4.1.36.Final:compile
| ......
+-com.datastax.cassandra:cassandra-driver-core:jar:3.6.0:compile
| +-io.netty:netty-handler:jar:4.0.56.Final:compile
| | +-io.netty:netty-buffer:jar:4.0.56.Final:compile
| | | -(io.netty:netty-common:jar:4.0.56.Final:compile - omitted for conflict with 4.1.36)
| | +-io.netty:netty-transport:jar:4.0.56.Final:compile
| | | -(io.netty:netty-buffer:jar:4.0.56.Final:compile - omitted for duplicate)
| | -io.netty:netty-codec:jar:4.0.56.Final:compile
| | -(io.netty:netty-transport:jar:4.0.56.Final:compile - omitted for duplicate)
从这个结果可以看出,编译的版本是4.1.36,而Cassandra引入的依赖版本是4.0.56,但是4.0.56并没有被载入。那么这两个版本的jar包有什么不同呢?由于报错的类是io.netty.util.concurrent.MultithreadEventExecutorGroup,王小谦查看了两个不同版本的MultithreadEventExecutorGroup源码,发现报错的行的代码果然是不一样的。于是产生了一个猜想:Cassandra需要的版本是由它自身引入的4.0.56,而不是4.1.36。
接下来我们需要验证4.0.56的可行性:王小谦用的IDE是IntelliJ,于是我们从Project Structure --> library中找到4.1.36的包,然后把它的class和source替换成本地的4.0.56。发现程序可以正常启动,这个错误没有再出现。
于是最后得出结论,我们需要的是4.0.56的jar包,而不是4.1.36。
最终的解决方法:顺着依赖树找到4.1.36的jar包的引入来源,在pom里添加<exclusion>把io.netty:netty-common排除在外。这样我们程序里就只剩下从Cassandra引入的4.0.56版本啦。
禁止转载。
英文版看这里:
VeromcaWang/SDEKnowledgegithub.com