工程的继承
工程的继承
继承描述的是两个工程间的关系,与java中的继承相似,子工程可以继承父工程中的配置信息,常见于依赖关系的继承。
作用:
- 简化配置
- 减少版本冲突
子工程的开发步骤
-
创建Maven模块,设置打包类型为pom
<packaging>pom</packaging>
注意事项:建议父工程打包方式为pom
-
在父工程的pom文件中配置依赖关系(子工程将沿用父工程中的依赖关系)
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.10.RELEASE</version> </dependency> ... </dependencies>
-
配置子工程中可选的依赖关系
<!--定义依赖管理--> <dependencyManagement> <dependencies> <!--代表子类不一定使用,子工程要用需要在子工程中声明,但不用写版本号--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> </dependencyManagement>
-
在子工程中配置当前工程所继承的父工程
<!--配置当前工程继承自parent工程--> <parent> <groupId>com.charley</groupId> <artifactId>maven_01_parent</artifactId> <version>1.0-SNAPSHOT</version> <relativePath>../maven_01_parent/pom.xml</relativePath> </parent>
-
在子工程中配置使用父工程中可选依赖的坐标
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies>
注意事项:子工程中使用父工程的可选依赖时,仅需要提供群组id和项目id,无需提供版本,版本由父工程统一提供,避免版本冲突子工程中还可以定义父工程中没有定义的依赖关系。
继承与聚合的区别
- 作用
- 聚合用于快速构建项目
- 继承用于快速配置
- 相同点
- 聚合与继承的pom.xml文件打包方式均为pom,可以将两种关系制作到同一个pom文件中
- 聚合与继承均属于设计型模块,并无实际的模块内容
- 不同点:
- 聚合是在当前模块中配置关系,聚合可以感知到参与聚合的模块有哪些
- 继承是在子模块中配置关系,父模块无法感知哪些子模块继承了自己