如何为Java依赖指定精确Jar版本?求助解决依赖版本冲突
解决Maven依赖版本冲突:为特定测试依赖指定精确的传递依赖版本
当然有办法搞定这个问题!核心思路就是切断exampleserver自带的sshd-core传递依赖,然后单独为测试环境引入匹配它的0.14.0版本,这样项目主代码用你的1.6.0,测试代码里的exampleserver就能用它需要的0.14.0了,完美隔离版本差异。
具体操作分两步来:
1. 排除exampleserver的sshd-core传递依赖
修改pom.xml里的exampleserver依赖项,添加<exclusions>标签把它自带的sshd-core排除掉:
<dependency> <groupId>com.another.project.server</groupId> <artifactId>exampleserver</artifactId> <version>1.0</version> <type>jar</type> <scope>test</scope> <exclusions> <!-- 移除exampleserver传递过来的sshd-core依赖 --> <exclusion> <groupId>org.apache.sshd</groupId> <artifactId>sshd-core</artifactId> </exclusion> </exclusions> </dependency>
2. 单独为测试环境引入sshd-core 0.14.0
在pom.xml里新增一个仅作用于测试环境的sshd-core依赖,版本指定为0.14.0:
<dependency> <groupId>org.apache.sshd</groupId> <artifactId>sshd-core</artifactId> <version>0.14.0</version> <scope>test</scope> </dependency>
配置生效后的效果
- 项目主代码(
compilescope)会正常使用你指定的sshd-core 1.6.0 - 测试代码(
testscope)会加载sshd-core 0.14.0,完全匹配exampleserver的版本要求,不会再因为实现差异导致运行失败
验证依赖版本
你可以用Maven命令查看依赖树,确认版本是否正确隔离:
mvn dependency:tree -Dincludes=org.apache.sshd:sshd-core
输出里应该能清晰看到两个版本:一个是compile scope的1.6.0,另一个是test scope的0.14.0。
内容的提问来源于stack exchange,提问作者Thao Nguyen
相关产品推荐
相关产品推荐

