在Maven中管理多个子项目的主要方式是:
- 使用元素定义子项目:
<project>
...
<modules>
<module>module1</module>
<module>module2</module>
</modules>
</project>
- 在子项目根目录下定义单独的pom.xml:
- parent
- pom.xml
- module1
- pom.xml
- module2
- pom.xml
- 子项目继承parent项目:
<parent>
<groupId>...</groupId>
<artifactId>...</artifactId>
<version>...</version>
<relativePath>../pom.xml</relativePath>
</parent>
- 在parent项目的pom.xml中定义依赖,供子项目继承:
<dependencyManagement>
<dependencies>
<dependency>...</dependency>
</dependencies>
</dependencyManagement>
子项目从parent项目继承依赖后,无需再次声明相同的依赖,直接使用即可。
- 使用mvn install在parent项目下构建所有子项目。
来看一个简单示例:
parent项目pom.xml:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0</version>
<modules>
<module>module1</module>
<module>module2</module>
</modules>
</project>
module1/pom.xml:
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
</project>
module2/pom.xml:
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
</project>
编译整体项目:
mvn install
所以,通过父子项目模块,Maven可以很好的管理多个相关联的子项目。