maven 中parent 与 dependencyManagement

来源:互联网 发布:大数据平台有哪些用户 编辑:程序博客网 时间:2024/06/11 09:06

今天我们来说说maven的pom.xml文件中parent,dependencyManagement 标签。

首先我们来说说parent标签,其实这个不难解释,就是父的意思,pom也有继承的。比方说我现在有A,B,C,A是B,C的父级。现在就是有一个情况B,C其实有很多jar都是共同的,其实是可以放在父项目里面,这样,让B,C都继承A就方便管理了。

子模块的写法如下:

<parent>          <groupId>com.lala</groupId>          <artifactId>my-parent</artifactId>          <version>0.0.1</version>      </parent>  

现在说说dependencyManagement 标签,其实这个也很好理解,比方说你的A项目pom文件内容如下

<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.lala</groupId>      <artifactId>my-parent</artifactId>      <version>0.0.1</version>      <packaging>pom</packaging>        <properties>          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>      </properties>        <dependencies>          <dependency>              <groupId>junit</groupId>              <artifactId>junit</artifactId>              <version>4.11</version>              <scope>test</scope>          </dependency>          <dependency>              <groupId>redis.clients</groupId>              <artifactId>jedis</artifactId>              <version>2.4.0</version>              <scope>provided</scope>          </dependency>      </dependencies>        <dependencyManagement>          <dependencies>              <dependency>                  <groupId>javax.mail</groupId>                  <artifactId>javax.mail-api</artifactId>                  <version>1.5.3</version>                  <scope>provided</scope>              </dependency>          </dependencies>      </dependencyManagement>        <build>          <plugins>              <plugin>                  <groupId>org.apache.maven.plugins</groupId>                  <artifactId>maven-compiler-plugin</artifactId>                  <version>3.3</version>                  <configuration>                      <source>1.8</source>                      <target>1.8</target>                      <verbose>true</verbose>                  </configuration>              </plugin>          </plugins>      </build>  </project>  

在dependencyManagement标签包围的jar里面,B,C是没有继承的,也就是不会自动引入的,你要 在子项目中显示的声明一些依赖才可以引入父项目

的jar(不需要指定version,scope).parent标签是将父项目的依赖,子项目会自动引入的,这也是两者的区别。

就是说如果B,C现在想引用A中的jar了,在dependencyManagement里面的jar,你直接在B,C中写<parent>标签是没有用的,不会自动引入的,

如果你想引用上诉父类A中的javax.mail-api架包,还要重写一下<groupId> ,<artifactId>(<version>标签可以不写)。

有些人会说这样做有什么意义?为什么不直接全部引用呢?这里就可能有这么一个例子,比方说B,C中需要大部分A中的jar,但有有个别jar B,C

不需要的,而且B,C不需要jar可能还不一样,这时候就需要dependencyManagement标签去选择了





原创粉丝点击