Maven 模块管理
多模块管理
在软件开发中,把一个大项目分拆为多个模块是降低软件复杂度的有效方法。
多模块管理简单地理解就是一个 Java 工程项目中不止有一个 pom.xml 文件,会在不同的目录中有多个这样的文件,进而实现 Maven 的多模块管理。
pom 文件编写注意事项
1、父 pom 中的 <packaging>
为 pom ,而不是 jar。
...
<modelVersion>4.0.0</modelVersion>
<groupId>com.drawcode</groupId>
<artifactId>detail-page</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging> <!-- 此处必须为pom -->
<name>detail-page</name>
...
2、父 pom 中的 <modules>
即为父子关系
<!-- modules即为父子关系 -->
<modules>
<module>detail-client</module>
<module>detail-service</module>
<module>detail-start</module>
</modules>
3、父 pom 中的 <dependencyManagement>
,相当于一个对所依赖 jar 包进行版本管理的管理器。
在父 POM 文件中,我们会看到 dependencyManagement 元素。通过它来管理 jar 包的版本,让子项目中引用一个依赖而不用显示的列出版本号。Maven 会沿着父子层次向上走,直到找到一个拥有 dependencyManagement 元素的项目,然后它就会使用在这个 dependencyManagement 元素中指定的版本号。
如果子 pom 中的 dependencies 中的 dependency 声明了 version,那么无论 dependencyManagement 中有无对该 jar 的 version 声明,都以 dependency 里的 version 为准。
4、父 POM 的 <plugins>
为空。
<build>
<plugins>
<!-- 注意此处为空 -->
</plugins>
</build>
5、子 pom 的 <packaging>
要配置为jar
6、子 pom.xml 不必添加 dependencyManagement
7、启动类所在的子模块,其需添加 plugin
<build>
<plugins>
<!--因为启动类在detail-start中,所以此处必须添加该plugin-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
模块的依赖与继承
如果 module-a 依赖 module-a,只需要在 module-a 的 pom.xml 文件中,引入 module-b 即可:
...
<dependencies>
<dependency>
<groupId>com.itranswarp.learnjava</groupId>
<artifactId>module-b</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
对于模块的继承,严格按照 pom 文件的编写规范,对父 pom 和子 pom 进行编写。
参考资源
1.https://www.liaoxuefeng.com/wiki/1252599548343744/1309301243117601
2.https://cloud.tencent.com/developer/article/1667275
每天学习一点点,每天进步一点点。