zoukankan      html  css  js  c++  java
  • Maven中dependencyManagement标签的正确使用方法

    前言

      Maven中的dependencyManagement元素提供了一种管理依赖版本号的方式,她用于声明所依赖的jar包的版本号等信息。当所有子项目再次引入这些jar包时,则无需显式的定义version属性。Maven会沿着父子层级向上寻找拥有dependencyManagement 元素的项目,然后继承它约定的版本号。

    使用方法

      pom文件中,有两种途径判断jar的版本号。

    • 子项目未声明依赖版本号,则继承父项目中的。如果dependency标签未曾声明version元素,那么maven就会到父项目dependencyManagement标签里面去找该artifactId和groupId 的版本声明信息,如果找到了,就继承它;否则,就会抛出异常,告诉你必须为dependency声明version属性。

    • 子项目定义的依赖版本号优先级高于父项目的。如果dependency标签声明了version属性,那么无论dependencyManagement中有无对该jar的version声明,都以dependency里的为准。

      在父项目的POM.xml中配置dependencyManagement标签,定义基本的父依赖。这里仅仅定义一个Junit5的依赖:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.wiener</groupId>
        <artifactId>springBoot</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <modules>
            <module>wiener-demo</module>
        </modules>
        <!--打包方式pom-->
        <packaging>pom</packaging>
    
        <properties>
    		<junit-jupiter.version>5.5.2</junit-jupiter.version>
        </properties>
    
        <!--   版本管理,导入需要的模块-->
        <dependencyManagement>
          <dependencies>
    	   <!-- junit 5 -->
    	   <dependency>
    	      <groupId>org.junit.jupiter</groupId>
    	      <artifactId>junit-jupiter-engine</artifactId>
    	      <version>${junit-jupiter.version}</version>
    	      <scope>test</scope>
    	   </dependency>
            </dependencies>
         </dependencyManagement>
    
        <build>
        </build>
    </project>
    

      在wiener-demo(pom.xml)中定义Junit5依赖:

    //子项目实际引用的jar包 
    <dependencies>
    	<!-- junit 5 -->
    	<dependency>
    		<groupId>org.junit.jupiter</groupId>
    		<artifactId>junit-jupiter-engine</artifactId>
    	</dependency>
     </dependencies>
    

      modules标签中的模块就是项目的子模块,他们都受到父模块的版本约束,但是需要自己导入子模块的依赖。dependencyManagement标签定义项目通用的父依赖,各个依赖的版本号由properties标签定义,通过${变量名}的形式动态获取版本号。

      例如,在父依赖中junit5依赖的版本号5.5.2就定义在properties标签中,变量名是junit-jupiter.version,而dependencyManagement标签通过${junit-jupiter.version}导入版本号;在用到Junit5依赖的子模块中,只需声明依赖,无需描述版本信息。

    结束语

      在顶层pom文件中,通过标签dependencyManagement定义公共的依赖关系,让所有的子项目使用依赖项的统一版本,确保应用的各个项目的依赖项和版本一致,保证测试的和发布的是相同的结果。

      这样做的优点是避免在每个子项目里都声明一个版本号,当想升级或切换到另一个版本时,只需要在顶层父容器里更新,而避免逐个修改子项目;另外如果某个子项目需要另外的一个版本,只需要在子项目声明version即可。温馨提示,dependencyManagement标签中定义的只是依赖的声明,并不实现引入,因此子项目需要显式的声明需要用的依赖。


      读后有收获,小礼物走一走,请作者喝咖啡。

    赞赏支持

  • 相关阅读:
    预习非数值数据的编码方式
    预习原码补码
    C语言||作业01
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
    C语言|作业12—学期总结
    C语言|博客作业11
    第三章预习
  • 原文地址:https://www.cnblogs.com/east7/p/14353536.html
Copyright © 2011-2022 走看看