Maven:改为在第三方依赖项中使用 Shade 版本

标签 maven maven-shade-plugin

假设我的项目名为A,Foo和Bar是第三方库。 A 取决于 Foo 版本 1 和 Bar。 Bar 取决于 Foo 版本 2:

A -> Foo version 1  
  \-> Bar  
      \-> Foo version 2

在我的项目 A 的 POM 中使用此 Maven 阴影插件配置

<relocation>
  <pattern>Foo</pattern>
  <shadedPattern>FooA</shadedPattern>
</relocation>

我使用的版本,Foo 版本 1,将被重命名/重新定位为 FooA。

问题:是否可以重命名/重新定位 Foo 版本 2?我知道如果我可以修改 Bar 的 POM,就可以做到这一点 - 但是,我不能,因为我不是 Bar 的经销商。

最佳答案

Maven 不允许依赖同一 Artifact 的多个版本。依赖解析的工作原理如下:

Maven picks the "nearest definition". That is, it uses the version of the closest dependency to your project in the tree of dependencies. You can always guarantee a version by declaring it explicitly in your project's POM. Note that if two dependency versions are at the same depth in the dependency tree, the first declaration wins.

"nearest definition" means that the version used will be the closest one to your project in the tree of dependencies. For example, if dependencies for A, B, and C are defined as A -> B -> C -> D 2.0 and A -> E -> D 1.0, then D 1.0 will be used when building A because the path from A to D through E is shorter. You could explicitly add a dependency to D 2.0 in A to force the use of D 2.0.

来源:Introduction to the Dependency Mechanism

就像 this answer 中所建议的那样解决方案可能是为存在此类冲突的每个模块生成阴影 JAR。以你的例子来说,这将是

  • 创建一个模块“Bar-shaded”,该模块创建“Bar”的阴影 JAR 及其所有依赖项
  • 在模块“A”中添加对“Foo”版本 1 和“Bar-shaded”的依赖项

关于Maven:改为在第三方依赖项中使用 Shade 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52697518/

相关文章:

gradle - 影子 jar 不将依赖项包含到 fat jar 中

maven - 过滤资源 maven-shade-plugin

java - 使用 Selenium 的页面对象设计模式是否创建页面类并通过它们的对象调用它们的构造函数?

java - maven-shade-plugin 不包括声明为依赖项的 jar

Maven 阴影插件 : deploy both artifacts but make shaded one the main

shell - maven zip uber-jar 和 shell 脚本

scala - 类似于 SBT 的 maven-shade 插件

java - 为最终程序获取 noClassDefFoundError

java - 当IntelliJ运行Maven项目时, "under the hood"会发生什么?

java - WSDL URL 的 Maven 过滤