乐闻世界logo
搜索文章和话题

How to manage Maven multi-module projects? What are the differences between aggregation and inheritance?

2月18日 21:27

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:

  1. Clear code organization, dividing modules by function or layer
  2. Unified dependency management, avoiding version conflicts
  3. High build efficiency, can build specific modules individually
  4. Facilitates team collaboration, different teams responsible for different modules
  5. 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 project
  • mvn clean install -pl module-a: build only module-a
  • mvn clean install -pl module-a -am: build module-a and its dependent modules
  • mvn clean install -pl '!module-a': build all modules except module-a
标签:Maven