SpringBoot项目Maven依赖版本冲突,Maven Shading插件无效求助
解决SpringBoot依赖版本冲突:同时使用新旧版本的可行方案
这种场景完全可行,核心是通过Maven Shade插件的包重命名功能,把其中一个版本的依赖挪到新的包路径下,让两个版本在运行时各占一个“独立空间”,不会互相干扰。你之前用Shade没生效,肯定是配置没踩对关键点。
正确配置步骤(拿实际场景举例)
假设:
- 你的代码要用到
com.example:artifact:2.0.0(新版本) - 第三方依赖
com.thirdparty:lib:1.0.0硬要依赖com.example:artifact:1.0.0(旧版本,和新版本不兼容)
1. 先把两个版本的依赖在pom里理清楚
先排除第三方依赖自带的旧版本,再单独引入旧版本并标记为provided(避免Maven自动用新版本覆盖),新版本正常引入:
<dependencies> <!-- 你的代码用的新版本,正常引入 --> <dependency> <groupId>com.example</groupId> <artifactId>artifact</artifactId> <version>2.0.0</version> </dependency> <!-- 第三方依赖,排除它自带的旧版本artifact --> <dependency> <groupId>com.thirdparty</groupId> <artifactId>lib</artifactId> <version>1.0.0</version> <exclusions> <exclusion> <groupId>com.example</groupId> <artifactId>artifact</artifactId> </exclusion> </exclusions> </dependency> <!-- 单独引入旧版本,标记为provided,交给Shade插件处理 --> <dependency> <groupId>com.example</groupId> <artifactId>artifact</artifactId> <version>1.0.0</version> <scope>provided</scope> </dependency> </dependencies>
2. 配置Shade插件重命名旧版本的包
重点是relocations节点,把旧版本的包路径改成新的(比如com.example.artifact改成com.example.artifact.v1),同时要指定只对旧版本的依赖做重命名,别碰新版本:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.4.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <relocations> <!-- 把旧版本的包重命名到v1路径下 --> <relocation> <pattern>com.example.artifact</pattern> <shadedPattern>com.example.artifact.v1</shadedPattern> <!-- 明确只处理旧版本的依赖 --> <includes> <include>com.example:artifact:1.0.0</include> </includes> </relocation> </relocations> <!-- 确保新版本的包原封不动保留 --> <filters> <filter> <artifact>com.example:artifact:2.0.0</artifact> <includes> <include>com/example/artifact/**</include> </includes> </filter> </filters> </configuration> </execution> </executions> </plugin> </plugins> </build>
3. 验证结果
执行mvn clean package后,打开生成的jar包看看:
com/example/artifact/**下是2.0.0版本的类(你的代码直接用这个路径)com/example/artifact/v1/**下是1.0.0版本的类(Shade插件会自动修改第三方依赖的字节码,把它对旧版本的引用改成这个新路径)
这样第三方依赖会乖乖用旧版本,你的代码用新版本,启动就不会冲突了。
踩坑排查
- 打包后只有新版本:检查
relocations里的includes是不是指定了旧版本;另外确认旧版本依赖的scope是provided,不然Maven会自动用新版本覆盖旧版本。 - 第三方依赖还是报错:用反编译工具打开第三方的类,看看import语句是不是已经变成重命名后的路径,要是没改,说明Shade插件没处理到,检查配置里的
relocation规则。 - 和SpringBoot插件冲突:如果用了
spring-boot-maven-plugin,要确保Shade插件在它之前执行,或者把Shade的phase设为package,SpringBoot插件会基于Shade后的jar重新打包。
内容的提问来源于stack exchange,提问作者user24923987
相关产品推荐
相关产品推荐

