POM dependencies与dependencyManagement区别

官网对dependencyManagement说明如下:

dependencyManagement: is used by POMs to help manage dependency information across all of
 its children. If the my-parent project uses dependencyManagement to define a dependency 
on junit:junit:4.0, then POMs inheriting from this one can set their dependency giving the
 groupId=junit and artifactId=junit only, then Maven will fill in the version set by the 
parent. The benefits of this method are obvious. Dependency details can be set in one 
central location, which will propagate to all inheriting POMs. 

Note that the version and scope of artifacts which are incorporated from transitive 
dependencies are also controlled by version specifications in a dependency management
 section. This can lead to unexpected consequences. Consider a case in which your project
 uses two dependences, dep1 and dep2. dep2 in turn also uses dep1, and requires a 
particular minimum version to function. If you then use dependencyManagement to specify an 
older version, dep2 will be forced to use the older version, and fail. So, you must be 
careful to check the entire dependency tree to avoid this problem; mvn dependency:tree is
 helpful.

dependencyManagement元素来管理依赖包版本,让子项目中引用一个依赖而不用显示的列出版本号。Maven会沿着父子层次向上走,直到找到一个拥有dependencyManagement元素的项目,然后它就会使用在这个dependencyManagement元素中指定的版本号。

相对于dependencyManagement,所有生命在dependencies里的依赖都会自动引入,并默认被所有的子项目继承。

那么如果在parent pom文件中分别定义了dependencies和dependencyManagement,它们的不同是:

  •          dependencies:子POM会完全继承父POM中声明的dependencies,如果子POM中没有声明某个依赖项,但是父POM中声明了该依赖项,就会直接从父POM中继承该依赖项,如果子POM也声明另外相同依赖包,那么子POM会覆盖父POM中依赖声明。
  •          dependencyManagement里只是声明依赖,并不实现引入,除非子POM显示声明需要用该依赖项。如果不在子POM中声明依赖,是不会从父POM中继承依赖的;只有在子POM中声明了该依赖项,并且没有指定具体版本,才会从父POM中继承该项,并且version和scope都读取自父POM;另外如果子POM中指定了版本号,那么会使用子POM中指定的jar版本。
  •  

猜你喜欢

转载自blog.csdn.net/pursuer211/article/details/82251854
今日推荐