Maven中dependencyManagement和dependencies区别?

Maven使用dependencyManagement元素提供了一种管理依赖版本号的方式。

通常会在一个组织或项目的最顶层的父pom中看到dependencyManagement元素。

使用pom.xml中的dependencyManagement元素能让所有在子项目中引用一个依赖不用显示的列出版本号。

Maven会沿着父子层次向上走,直到找到一个拥有dependencyManagement元素的项目,然后他就会使用这个

dependencyManagement元素中指定的版本号。

例如在父项目里:

<dependencyManagement>
      <dependencies>
        <!--springboot 2.2.2-->
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-dependencies</artifactId>
          <version>2.2.2.RELEASE</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>

        <!--spring cloud Hoxton.SR1-->
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-dependencies</artifactId>
          <version>Hoxton.SR1</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>

        <!--spring cloud alibaba 2.1.0-->
        <dependency>
          <groupId>com.alibaba.cloud</groupId>
          <artifactId>spring-cloud-alibaba-dependencies</artifactId>
          <version>2.1.0.RELEASE</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>


        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${mysql.version}</version>
        </dependency>

        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>${druid.version}</version>
        </dependency>

        <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>${mybatis.spring.boot.version}</version>
        </dependency>
      </dependencies>
  </dependencyManagement>

然后在子项目里就可以不添加版本号,例如:

  <dependencies>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
        </dependency>

        <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
       </dependency>
</dependencies>

这样的好处就是:如果有多个子项目都引用同一个依赖,则可以避免在每个使用的子项目里都声明一个版本号,这样当想升级或切换版本是就可以直接在父项目里修改。所有子项目都改变了版本号。

dependencyManagement里只是声明依赖,并不实现引入,因此子项目需要显示是吗需要用的依赖。

如果子项目里指定了版本号,则用子项目的版本。

发布了40 篇原创文章 · 获赞 24 · 访问量 1772

猜你喜欢

转载自blog.csdn.net/qq_40807366/article/details/105056340