在 Maven 中排除依赖冲突主要有以下 5 种方法,结合具体场景说明操作步骤:
标签)适用场景:排除直接依赖中的传递性冲突包
示例:排除 spring-boot-starter-web
中的 Tomcat 依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-tomcatartifactId>
exclusion>
exclusions>
dependency>
要点:
适用场景:冲突由间接依赖(非直接引入)引起
示例:模块 A 依赖模块 B,而 B 传递了冲突库 hsqldb
<dependency>
<groupId>com.examplegroupId>
<artifactId>module-aartifactId>
<exclusions>
<exclusion>
<groupId>org.hsqldbgroupId>
<artifactId>hsqldbartifactId>
exclusion>
exclusions>
dependency>
原理:
A → B → hsqldb
hsqldb
即可切断传递链dependencyManagement
)适用场景:统一管理多模块项目的依赖版本
示例:父 POM 强制所有子模块使用安全的 log4j
版本
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.17.1version>
dependency>
dependencies>
dependencyManagement>
效果:子模块无需声明版本号,自动继承父 POM 的版本
场景:杜绝某依赖被任何途径引入(如高危漏洞库)
操作:
log4j:log4j:1.0-empty
)<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.0-emptyversion>
dependency>
原理:Maven 依赖仲裁优先选择最短路径的空包版本
场景:排除运行时依赖但保留编译能力
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<scope>providedscope>
dependency>
效果:
provided
:编译有效,不打包test
:仅测试有效,不打包maven-enforcer-plugin
)场景:防止其他成员意外引入冲突依赖
配置:在父 POM 添加规则
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-enforcer-pluginartifactId>
<executions>
<execution>
<id>ban-conflict-libid>
<configuration>
<rules>
<bannedDependencies>
<excludes>
<exclude>com.alibaba:fastjsonexclude>
excludes>
<searchTransitive>truesearchTransitive>
bannedDependencies>
rules>
configuration>
execution>
executions>
plugin>
效果:若有人引入 fastjson
,构建直接失败
方法 | 适用场景 | 优势 | 局限性 |
---|---|---|---|
|
简单直接依赖冲突 | 精准排除单个依赖 | 需手动定位冲突源 |
dependencyManagement |
多模块版本统一 | 全局版本控制 | 不适用于非版本冲突场景 |
空包替换 | 彻底封杀高危依赖 | 一劳永逸 | 需私服权限,维护成本高 |
Enforcer 插件 | 团队协作防误引入 | 强制规范,提前拦截 | 配置复杂 |
优先使用基础排除法,对团队协作项目推荐 dependencyManagement + Enforcer 插件组合 。
排查依赖树命令:mvn dependency:tree -Dincludes=groupId:artifactId