Maven's Multi-Module Project manages complex project structures through Aggregation and Inheritance mechanisms. These two mechanisms can be used separately or in combination.
1. Aggregation:
Aggregation is used to combine multiple modules for building together, by declaring submodules using the <modules> tag in the parent POM. When building the parent project, Maven automatically builds all submodules.
xml<project> <groupId>com.example</groupId> <artifactId>parent-project</artifactId> <packaging>pom</packaging> <modules> <module>module-a</module> <module>module-b</module> <module>module-c</module> </modules> </project>
2. Inheritance:
Inheritance is used to share parent POM configurations in submodules, by referencing the parent POM using the <parent> tag in the child POM. Submodules can inherit dependency management, plugin configurations, properties, etc. from the parent POM.
xml<project> <parent> <groupId>com.example</groupId> <artifactId>parent-project</artifactId> <version>1.0.0</version> </parent> <artifactId>module-a</artifactId> </project>
Common Configurations in Parent POM:
<dependencyManagement>: uniformly manage dependency versions, submodules only need to declare groupId and artifactId<pluginManagement>: uniformly manage plugin configurations<properties>: define common properties, such as version numbers, encoding formats, etc.<dependencies>: define dependencies shared by all submodules<build>: define common build configurations
Advantages of Multi-Module Projects:
- Clear code organization, dividing modules by function or layer
- Unified dependency management, avoiding version conflicts
- High build efficiency, can build specific modules individually
- Facilitates team collaboration, different teams responsible for different modules
- Supports parallel builds, improving build speed
Best Practices:
- Parent POM's packaging must be pom
- Submodules reference each other through dependency relationships, avoid circular dependencies
- Use relative paths to reference submodules, facilitating project migration
- Use
<dependencyManagement>in parent POM to uniformly manage versions - Reasonably divide module granularity, avoiding too many or too few modules
Common Commands:
mvn clean install: build the entire projectmvn clean install -pl module-a: build only module-amvn clean install -pl module-a -am: build module-a and its dependent modulesmvn clean install -pl '!module-a': build all modules except module-a