Maven知识点扫盲(二)依赖管理

DependencyManagement

引入

在多模块的项目中,如果在父pom中使用dependencies来管理依赖,那么在子模块中,无论是否需要父pom中的依赖,都会强制的继承过来,这样就不太有很好了。可以简单的理解为Java中的implements 无论是否需要,都要实现父类中的所有依赖的。而dependencyManagement不是这样的,只是提供了子模块中可能用到的一些依赖,不会强制子模块引入依赖,而这个就像是Java中的abstract Class,具体要不要实现父类中的依赖,完全由子模块来决定。

实例

父pom

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactid>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactid>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>
  </dependencies>
</dependencyManagement>

子模块Pom

<dependency>
    <groupId>junit</groupId>
    <artifactid>junit</artifactId>
  </dependency>
  <dependency>
    <groupId>log4j</groupId>
    <artifactid>log4j</artifactId>
  </dependency>

这样一来,就变得容易管理,使得各个子模块中的依赖的版本&scode是一样的,不存在出现重复依赖。|== 关键的地方是在父POM中的dependencyManagement标签中配置的依赖是不会主动引入到子项目中的、也就是说虽然在父POM中的dependencyManagement定义了junit的依赖、假如子类中没有关于junit的、那么子类就没有junit依赖的引入、并且假如子项目不想使用4.1版本的junit、还可以指定自己想要使用的junit版本、这样就完全覆盖了父POM中关于junit的定义、也就是说父POM中的junit定义与他无关。

更进一步

我们知道Maven的继承和Java的继承一样,是无法实现多重继承的,如果10个、20个甚至更多模块继承自同一个模块,那么按照我们之前的做法,这个父模块的dependencyManagement会包含大量的依赖。如果你想把这些依赖分类以更清晰的管理,那就不可能了,import scope依赖能解决这个问题。你可以把dependencyManagement放到单独的专门用来管理依赖的POM中,然后在需要使用依赖的模块中通过import scope依赖,就可以引入dependencyManagement。

依赖范围有一种是import、是只有在dependencyManagement元素下才有效果的、使用该范围的依赖通常指向一个POM、作用是将目标POM中的dependencyManagement配置导入并合并到当前POM的dependencyManagement元素中。

实例

A pom

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.volshell.sample</groupId>
  <artifactId>A</artifactId>
  <packaging>pom</packaging>
  <version>1.0-SNAPSHOT</version>
  <dependencyManagement>
    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactid>junit</artifactId>
          <version>4.8.2</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>log4j</groupId>
          <artifactid>log4j</artifactId>
          <version>1.2.16</version>
        </dependency>
    </dependencies>
  </dependencyManagement>
</project>

B pom

<dependencyManagement>
    <dependencies>
        <dependency>
          <groupId>com.volshell.sample</groupId>
          <artifactid>A</artifactId>
          <version>1.0-SNAPSHOT</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
    </dependencies>
  </dependencyManagement>

  <dependency>
    <groupId>junit</groupId>
    <artifactid>junit</artifactId>
  </dependency>
  <dependency>
    <groupId>log4j</groupId>
    <artifactid>log4j</artifactId>
  </dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值