Maven中父子项目依赖传递详解

父子项目依赖传递实现方式

  1. 首先创建父项目

    1. 先创建一个项目example-trains-father.

    2. 添加父项目打包方式,直接在URL下面添加,即是<project></project>结构体内的

      <!-- 父项目打包方式 -->
        <packaging>pom</packaging>
      
    3. 给父项目添加相关依赖

      在<properties></properties>结构体中,可以通过下列语句定义版本号:
      	<junit.version>4.11</junit.version>
          <spring.version>5.2.8.RELEASE</spring.version>
      然后在<dependecies></dependecies>(其他地方应该也可以)中可以使用${junit.version}的方式,调用版本号,即${junit.version} = 4.11
      示例:
      	<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
          </dependency>
      
    4. 添加<dependencyManagement> </dependencyManagement>,也是在<project></project>结构体内的

      <!-- 父项目中同一管理的依赖:依赖容器,在子项目中使用的时候才会引入,父项目中并不会导入该类目的jar包 -->
      <dependencyManagement>
          <dependencies>
              <dependency>
                  <groupId>log4j</groupId>
                  <artifactId>log4j</artifactId>
                  <version>${log4j.version}</version>
              </dependency>
          </dependencies>
      </dependencyManagement>
      
  2. 再创建子项目

    1. 还是先创建一个项目example-trains-children.

    2. 在子项目中添加如下代码,实现继承关系,同样添加在<project></project>

      	<parent>
            	<groupId>org.example</groupId>
            	<artifactId>example-trains-father</artifactId>
           	<version>1.0-SNAPSHOT</version>
          	<relativePath>../exampletrainsfather/pom.xml</relativePath>
        	</parent>
      
        <!--子项目会自动继承父项目的groupId,所以子项目不需要再写groupId,因此将新建项目时写的groupId注释掉-->
        <!--<groupId>org.example</groupId>-->
      

      此时,子项目会自动导入父项目的<dependencies></dependencies>中的所有jar包

    3. 若要在子项目中的<dependencies></dependencies>添加父项目中的<dependencyManagement></dependencyManagement>中的依赖,则此时无需指定version,会自动加载父类指定的version

      <!--无需指定版本号-->
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
      </dependency>
      

      也就是通过实现了子项目依赖的统一管理。

注意点

父项目的打包方式必须是pom

<packaging>pom</packaging>

优点

  1. 通过父子项目,能够合理有效的复用依赖jar包
  2. 子项目相互独立更加便于敏捷开发和独立管理

缺点

父子项目之间的系统集成性能较差


版权声明:本文为weixin_43819429原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。