Maven多模块项目中,如何指定多个模块需要的依赖?

In a Maven multi-module project, how to specify dependency needed in more than one module?

我知道多模块 Maven 项目的目的是每个模块都可以单独编译和构建,也可以从父模块集中编译和构建。

假设我有两个 three modules need to use the Google Guava 图书馆。我是否在两个子模块中的每一个的 POM 中指定该依赖项?如果是这样,什么“范围”?或者我是否在父模块中指定依赖项?我需要将 Guava 捆绑在我的最终产品中,但我当然不需要两份。

Suppose two of my three modules need to use the Google Guava library. Do I specify that dependency in the POM of each of the two sub-modules?

这取决于这些模块之间的关系以及你用它们做什么;我们称它们为 moduleAmoduleB(共享依赖的模块)和 moduleC(第三个模块)。

如何部署 moduleAmoduleB?每个人都有自己的同一个图书馆副本有意义吗?

  • 例如,如果它们都是 运行 独立的 WAR,您需要为每个 WAR 提供它自己的库副本。
  • 如果它们都是以相同的 war 结尾的 jar(可能由 moduleC 表示),那么您需要为它们每个都提供 [=16= 的依赖关系],并在 moduleC 中使用默认范围添加第三个依赖项。

Or do I specify the dependency in the parent module?

在 parent 模块中指定依赖项的问题在于,moduleC 也会获取依赖项,这可能不是您想要的。

解决此问题的一种可能性(例如,如果 moduleAmoduleB 共享 很多 依赖项或公共属性或设置)是添加常见的 parent:

  • 用于 moduleAmoduleB 的额外 parent pom / reactor,但不适用于 moduleC
  • 这个额外的 parent pom 将在树中与 moduleC 处于同一级别(因此它会依次具有与 [=12= 相同的 parent ]).
  • 它将包含 moduleAmoduleB 的任何共同点。

我通常在父项目的 dependencyManagement 中声明所有依赖项,然后在模块的 depenencies 中使用它们,但没有 version。版本仅在父项目中声明。

至于scope,我通常不会在父类中声明范围,除非它是非常明显的东西,比如 JUnit。

Do I specify that dependency in the POM of each of the two sub-modules?

如果你直接使用这个依赖,那么是的。即使它会被传递包含。

If so, what “scope”?

这取决于依赖项是什么以及您如何使用它。 Guava 通常是 compile.

Or do I specify the dependency in the parent module?

您可以在父级的 dependencyManagement 中声明它,这样您就不必在其他任何地方指定版本。

但是你通常不会在父模块中声明依赖,因为它会被所有的子模块继承。这通常是一个过多的假设。

I need Guava bundled in my final product, but I certainly don't need two copies.

不会发生。