dependencyManagement和dependencies之间的区别是什么? 我在Apache Maven网站上看过文档。 在dependencyManagement下定义的依赖项似乎可以在其子模块中使用,而无需指定版本。

例如:

父项目(Pro-par)在dependencyManagement下定义了一个依赖项:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8</version>
    </dependency>
 </dependencies>
</dependencyManagement>

然后在Pro-par的子函数中,我可以使用junit:

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
  </dependency>
</dependencies>

但是,我想知道是否有必要在父pom中定义junit ?为什么不在需要的模块中直接定义它呢?


当前回答

就像你说的;dependencyManagement用于将所有依赖关系信息拉入一个公共POM文件,从而简化子POM文件中的引用。

当您有多个不想在多个子项目下重新输入的属性时,它就变得非常有用。

最后,dependencyManagement可用于定义工件的标准版本,以便在多个项目中使用。

其他回答

如果依赖项是在顶级pom的dependencyManagement元素中定义的,子项目就不必显式地列出依赖项的版本。如果子项目确实定义了一个版本,它将覆盖顶层中列出的版本 POM的依赖管理部分。也就是说,dependencyManagement版本仅为 当子进程没有直接声明版本时使用。

有几个答案概述了maven的< dependencies >和<dependencyManagement>标记之间的区别。

但是,下面简要阐述了几点:

<dependencyManagement> allows to consolidate all dependencies (used at child pom level) used across different modules -- clarity, central dependency version management <dependencyManagement> allows to easily upgrade/downgrade dependencies based on need, in other scenario this needs to be exercised at every child pom level -- consistency dependencies provided in <dependencies> tag is always imported, while dependencies provided at <dependencyManagement> in parent pom will be imported only if child pom has respective entry in its <dependencies> tag.

用我自己的话来说,你的父项目帮助你提供了两种依赖:

implicit dependencies : all the dependencies defined in the <dependencies> section in your parent-project are inherited by all the child-projects explicit dependencies : allows you to select, the dependencies to apply in your child-projects. Thus, you use the <dependencyManagement> section, to declare all the dependencies you are going to use in your different child-projects. The most important thing is that, in this section, you define a <version> so that you don't have to declare it again in your child-project.

在我看来,<dependencyManagement>(如果我错了请纠正我)只是通过帮助您集中依赖项的版本而有用。它就像一种辅助功能。 作为最佳实践,您的<dependencyManagement>必须在父项目中,其他项目将继承它。一个典型的例子是通过声明Spring父项目来创建Spring项目。

如果你无论如何都有一个parent-pom,那么在我看来,使用<dependencyManagement>只是为了控制版本(可能还有范围)是一种浪费空间的行为,而且会让初级开发人员感到困惑。

无论如何,在某种父-pom文件中,您可能会有版本的属性。为什么不直接在子pom中使用这个属性呢?这样,您仍然可以为所有子项目一次更新属性中的版本(在父-pom内)。这与<dependencyManagement>具有相同的效果,只是没有<dependencyManagement>。

在我看来,<dependencyManagement>应该用于“真正的”依赖项管理,比如排除等。

为了便于理解,这里作了解释。 dependencyManagement和dependencies之间的最终区别是声明和添加