IDEA 查看 Maven 依赖树与解决 Jar 包冲突
目录
- 一、查看依赖树
- 方法 1:IDEA 自带 Maven 工具
- 方法 2:使用命令行
- 方法 3:IDEA 插件(推荐)
- 二、找出冲突 jar 包
- 三、解决冲突(exclusion)
- 四、总结
模拟依赖冲突
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>6.0.9</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.3.23</version></dependency></dependencies>
一、查看依赖树
方法 1:IDEA 自带 Maven 工具
-
打开右侧 Maven 工具栏(快捷键
Alt+Shift+M
/View > Tool Windows > Maven
)。 -
找到你的项目,展开 Dependencies 节点。
- 这里能看到所有依赖树结构。
- 如果某个依赖有冲突,IDEA 通常会用 灰色/红色字体标注出被排除或版本冲突的 jar。
-
鼠标悬停在依赖上,可以看到它的 来源(哪个依赖引入的)。
方法 2:使用命令行
在项目根目录执行:
mvn dependency:tree
这会打印依赖树,例如:
[INFO] org.example:dependency-test:jar:1.0-SNAPSHOT
[INFO] +- org.springframework:spring-webmvc:jar:6.0.9:compile
[INFO] | +- org.springframework:spring-beans:jar:6.0.9:compile
[INFO] | +- org.springframework:spring-context:jar:6.0.9:compile
[INFO] | +- org.springframework:spring-core:jar:6.0.9:compile
[INFO] | | \- org.springframework:spring-jcl:jar:6.0.9:compile
[INFO] | +- org.springframework:spring-expression:jar:6.0.9:compile
[INFO] | \- org.springframework:spring-web:jar:6.0.9:compile
[INFO] | \- io.micrometer:micrometer-observation:jar:1.10.7:compile
[INFO] | \- io.micrometer:micrometer-commons:jar:1.10.7:compile
[INFO] \- org.springframework:spring-aop:jar:5.3.23:compile
org.springframework:spring-beans:jar:6.0.9:compile用的6.0.0的版本
如果树太大,可以加过滤:
mvn dependency:tree -Dincludes=org.springframework
方法 3:IDEA 插件(推荐)
安装 Maven Helper 插件(在 IDEA 插件市场搜索)。
-
打开
pom.xml
,底部会出现Dependency Analyzer
标签页。 -
在这个面板里,可以:
- 一键查看依赖树
- 高亮显示冲突 jar 包
- 直接右键选择 Exclude 依赖
二、找出冲突 jar 包
-
在依赖树里寻找 同一个 groupId + artifactId 但不同版本的依赖。
例如:org.springframework:spring-beans:6.0.9 org.springframework:spring-beans:5.3.23 (omitted for conflict)
表示
spring-beans
有两个版本冲突。 -
Maven 默认会选 路径最短(离项目最近)的依赖,其他版本就会被排除(omitted)。
但有时候这个版本并不是你想要的,就需要手动干预。
三、解决冲突(exclusion)
在 pom.xml
中找到冲突依赖的 上游依赖,添加 exclusion
。
例如,如果 spring-boot-starter
引入了错误的 commons-logging
,可以这样写:
<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>6.0.9</version><exclusions><exclusion><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId></exclusion></exclusions></dependency>
或者如果只是版本不一致,可以在 dependencyManagement
里强制指定版本:
<dependencyManagement><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>5.3.23</version></dependency></dependencies>
</dependencyManagement>
四、总结
- 快速看依赖树 → IDEA 自带依赖树 或
mvn dependency:tree
。 - 高效排查冲突 → 装 Maven Helper 插件,直观显示冲突。
- 解决冲突 → 用
exclusion
排除不需要的包,或在dependencyManagement
锁定版本。