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继承它。尽可能保持简单。如果一个项目需要A依赖项,则将其添加到pom文件中。不要让开发人员感到困惑。

其他回答

我在这个问题上迟到了,但我认为它值得一个比公认的回答更清晰的回答(公认的回答是正确的,但没有强调实际重要的部分,这需要您自己推断)。

在父POM中,<dependencies>和<dependencyManagement>之间的主要区别是:

Artifacts specified in the <dependencies> section will ALWAYS be included as a dependency of the child module(s). Artifacts specified in the <dependencyManagement> section, will only be included in the child module if they were also specified in the <dependencies> section of the child module itself. Why is it good you ask? Because you specify the version and/or scope in the parent, and you can leave them out when specifying the dependencies in the child POM. This can help you use unified versions for dependencies for child modules, without specifying the version in each child module.

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

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项目。

依赖项管理允许合并和集中管理依赖项版本,而不需要添加由所有子继承的依赖项。当你有一组继承共同父项的项目(即多个)时,这尤其有用。

dependencyManagement的另一个极其重要的用例是控制在传递依赖关系中使用的工件的版本。没有例子很难解释。幸运的是,文档中对此进行了说明。

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

<dependencyManagement>的一个用例是解决库版本冲突。

例子:

项目A有库x:1.0.1 项目A有B库 B库有库x:1.0.0

有了这个设置,你会得到项目A同时x:1.0.1和x:1.0.0的冲突。 要解决这个问题,您可以将特定版本的依赖项放入<dependencyManagement>标签中