up:: Maven 继承 tag::选择性继承

Maven 继承说到依赖可以继承,但是并不是每一个模块都需要引入父模块的所有依赖。例如一个工具模块,就不太需要 spring这些依赖包,但是因为继承关系,导致工具模块也引入了这些包,为了避免这种情况就需要使用新的元素 dependencyManagement。

dependencyManagement 可以让子类自行的选择继承父模块的依赖,只需要将父模块的依赖用元素 dependencyManagement包裹起来即可。例如父模块依赖代码如下:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>2.5.6</version>
    </dependency>
    
     <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>5.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

子模块引用父模块依赖,代码如下:

 <dependencies>
     <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
  </dependencies>

子模块 pom 直接引用所需要的依赖坐标即可,上面代码只引用了父模块的 junit 依赖,因此 spring-core 不会被引入。子模块还去掉了依赖的 version 和 scope 信息,这是因为继承了父模块的 pom,完整的依赖声明已经在父 pom 中了,因此子模块只需要 groupId 和 artifactId 就能获取对应的依赖信息,这样使用也能使所有子模块统一依赖版本,降低依赖冲突概率。