Maven中如何为特定子依赖指定非继承的依赖版本?
Maven实现单一依赖的组件版本指定
当然可以实现你要的需求,分两种情况处理:
仅需在依赖声明层级区分版本
如果只是希望在依赖树里体现E用F v1.0、C/D用F v2.0,直接用依赖排除+显式声明就能搞定:
- 在子项目B的
pom.xml里,给E的依赖加上排除规则,把它传递过来的F依赖删掉,避免继承父项目A的v2.0版本:
<dependency> <groupId>你的E的groupId</groupId> <artifactId>E</artifactId> <version>E的版本号</version> <exclusions> <exclusion> <groupId>F的groupId</groupId> <artifactId>F</artifactId> </exclusion> </exclusions> </dependency>
- 接着在B的
pom.xml里单独声明F v1.0的依赖:
<dependency> <groupId>F的groupId</groupId> <artifactId>F</artifactId> <version>1.0</version> </dependency>
不过要注意:Maven的依赖调解机制最终只会选一个版本(优先路径更短或声明顺序靠后的),所以这种方式下,C/D可能也会被迫用F v1.0,没法实现真正的运行时版本隔离。
需要实际运行时版本隔离(真正实现E用v1.0,C/D用v2.0)
如果要让E和C/D在运行时分别用不同版本的F,得用maven-shade-plugin把E和它依赖的F v1.0重打包,避免版本冲突:
- 先按上面的步骤排除E的F传递依赖,然后在B的
pom.xml里配置这个插件:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.5.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <!-- 把F的包路径重命名,和v2.0的包区分开 --> <relocations> <relocation> <pattern>com.example.F</pattern> <shadedPattern>com.example.shaded.F</shadedPattern> </relocation> </relocations> <!-- 只对E和F v1.0做重打包处理 --> <artifactSet> <includes> <include>com.example:E</include> <include>com.example:F:1.0</include> </includes> </artifactSet> </configuration> </execution> </executions> </plugin> </plugins> </build>
这么处理之后,E会用重命名后的F v1.0,C/D还是用父项目A里的F v2.0,真正实现了版本隔离。
内容的提问来源于stack exchange,提问作者PleaseHlep123
相关产品推荐
相关产品推荐

