假设项目B、C、D都要依赖于A项目,每个项目都有配置跟A一样的jar包依赖比较麻烦,可以采用其他项目继承于A的方式,可以让其他项目自动拥有A项目一样的jar包依赖。
新建项目:
我们让child项目继承于parent。
先打开parent的pom.xml:
<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.lee</groupId>
<artifactId>parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- 定义为父POM,其他项目继承这个父文件 -->
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<commons-lang3.version>3.1</commons-lang3.version>
<junit.version>4.12</junit.version>
</properties>
<!--
dependencyManagement元素既能让子模块继承父模块的配置,又能让子模块依赖使用灵活。
dependencyManagement元素下的依赖不会实际引入到子模块的依赖中,但能约束子模块的依赖使用,
如:一旦子模块需要使用这个依赖,版本号将被限制
-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 声明在dependecies元素的依赖将会被子模块继承 -->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
在child项目打开pom.xml:
<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>
<parent>
<groupId>com.lee</groupId>
<artifactId>parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
<artifactId>child</artifactId>
<packaging>jar</packaging>
<name>child</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency> -->
</dependencies>
</project>
这样child项目就继承了parent的junit的依赖:
因为dependencyManagement元素既能让子模块继承父模块的配置,又能让子模块依赖使用灵活。如果我们把child中pom.xml的注释放开:
<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>
<parent>
<groupId>com.lee</groupId>
<artifactId>parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
<artifactId>child</artifactId>
<packaging>jar</packaging>
<name>child</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
</project>
将会看到这样的提示:
同时jar包依赖情况如下:
正确声明应该是:
依赖如下: