这是我参与更文挑战的第23天,活动详情查看: 更文挑战
业务场景
在使用Maven进行项目包和依赖管理时, 可能会遇到依赖版本冲突的问题
假设项目中存在A/B/C三个依赖, 其中A/B是我们在pom中直接引入的, 例如:
<dependency>
<groupId>com.A</groupId>
<artifactId>A</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.B</groupId>
<artifactId>B</artifactId>
<version>2.0</version>
</dependency>
复制代码
而C依赖是A和B都需要的, 但它们各自引用的版本却不一致, A使用C的2.0版本, B使用C的5.0版本
如果C的两个版本之间没有破坏性更新, 这个问题还好说
倘若C在5.0版本中新加入了方法且B也使用了, 这时候Spring Boot就会抛出异常:
Description:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
C.Test.test(Test.java:38)
The following method did not exist:
C.Test.test()LC/Test;
The method's class, C.Test, is available from the following locations:
jar:file:/app/libs/C-2.0.jar!/C/Test.class
jar:file:/app/libs/C-5.0.jar!/C/Test.class
The class hierarchy was loaded from the following locations:
C.Test: file:/app/libs/C-2.0.jar
复制代码
报错信息其实已经很清楚了不是吗?
所以我们要做的, 就是在A中把2.0版本的C的依赖排除即可
方案
手动修改
如果我们的依赖非常清晰, 那直接进入pom文件, 在代码里增加排除即可:
<dependency>
<groupId>com.A</groupId>
<artifactId>A</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>com.C</groupId>
<artifactId>C</artifactId>
</exclusion>
</exclusions>
</dependency>
复制代码
利用Idea
如果我们的依赖错综复杂, 是个大项目, 且C的依赖藏得非常深, 手动修改显然是不现实的
这时候我们就要利用宇宙第一IDEIdea了
打开侧边的Maven工具栏, 点击按钮打开依赖结构:
按下Ctrl+F, 输入有冲突的依赖名称, 例如常用的jackson-core:
最后只需要右键->排除, 就搞定了:
总结
认真读异常, 先想再下手!
近期评论