Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 41 ยท Packaging and Multi-module

Multi-Module Builds and the Reactor

Split a Maven project into modules: aggregator POMs, the reactor build order, inter-module dependencies, -pl and -am, and inheritance versus aggregation.

A small project is one POM and one jar. A real application soon wants parts: a core library with the business rules, a service layer on top, a web or command-line module at the top. Keeping them in one project blurs the boundaries, and splitting them into separate repositories makes every change a multi-step dance. Maven's answer is the multi-module build: several modules in one repository, built together by one command.

This lesson covers the layout of such a project, how Maven decides the build order (the reactor), how modules depend on each other, how to build part of the project with -pl and -am, and the difference between two ideas that people constantly mix up: aggregation and inheritance. The commands and POMs are read-only, because they need a Maven installation. The runnable parts are Java stand-ins: a reactor ordering by topological sort and a model of -pl with -am. They follow the idea of Maven's algorithm, not its source. Make sure you know Parent POMs and the Effective POM and Coordinates first.

The layout

A multi-module project is a folder with a root POM and one subfolder per module, each with its own POM:

TEXT
shop/
  pom.xml            <- parent and aggregator, packaging pom
  shop-core/
    pom.xml
    src/main/java/...
  shop-service/
    pom.xml
    src/main/java/...
  shop-app/
    pom.xml
    src/main/java/...

The root POM has <packaging>pom</packaging> and lists the modules by folder name:

XML
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.shop</groupId>
  <artifactId>shop-parent</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <modules>
    <module>shop-core</module>
    <module>shop-service</module>
    <module>shop-app</module>
  </modules>
</project>

Running mvn verify in shop/ now builds all three modules in one run. Each module is a full project with its own jar. Maven 4 introduces a <subprojects> element with the same purpose and a newer model version; the idea is the same, so the rest of this lesson uses the Maven 3 spelling.

One repository, several modules

core Business rules. Depends on nothing.
service Uses core to do the work.
app Starts everything. Uses service.

Each module is its own jar with its own POM.

1 / 2

Dependencies between modules

When shop-service needs shop-core, it declares a normal dependency with the module's coordinates:

XML
<dependency>
  <groupId>com.example.shop</groupId>
  <artifactId>shop-core</artifactId>
  <version>${project.version}</version>
</dependency>

Using ${project.version} keeps modules in step: when the version is raised in the parent, the references follow (Properties and Build Settings shows how interpolation works). In the reactor build, Maven resolves shop-core from the module being built in the same run (its target/classes, or its jar when the build reaches package), not from ~/.m2. That is what lets you change core and service together and test both in a single command, without installing anything between steps.

The reactor

The reactor is the part of Maven that takes all modules, works out the order and runs the requested phases across them. The rules are simple:

  1. A module is built after every module it depends on. If service depends on core, then core goes first.
  2. A parent POM is built before its children, because children inherit from it.
  3. Among modules with no ordering constraint between them, Maven keeps the order in which they are listed in <modules>.

The order in <modules> therefore does not have to be the build order. You can list shop-app first, and Maven will still build shop-core first because of the dependencies. When the console starts, Maven prints the order it computed:

TEXT
[INFO] Reactor Build Order:
[INFO]
[INFO] shop-parent                                                        [pom]
[INFO] shop-core                                                          [jar]
[INFO] shop-service                                                       [jar]
[INFO] shop-app                                                           [jar]

If module A needs B and B needs A, there is no valid order, and Maven stops with a "cyclic reference" error before building anything. The fix is a design change: extract the shared part into a third module that both can depend on.

By default, a failure stops the build at the failing module and the rest are marked SKIPPED. -fae (fail at end) keeps building modules that do not depend on the failed one, and -fn never fails. After a failure, you can resume with -rf :shop-service ("resume from") instead of rebuilding everything before it.

flowchart LR
  P["shop-parent<br/>(pom)"] --> C["shop-core"]
  C --> S["shop-service"]
  S --> A["shop-app"]

The reactor builds the parent first, then each module after the modules it depends on.

Building a part: -pl and -am

On a large project you rarely want to build everything. These options select modules:

Option Meaning
-pl shop-service Build only this module (-pl = "projects list")
-pl :shop-service The same, selected by artifactId
-pl shop-core,shop-service Build several modules
-am Also make: add the modules the selection depends on
-amd Also make dependents: add the modules that depend on the selection
-rf :shop-service Resume from this module in the order

A frequent surprise: mvn -pl shop-service verify fails if shop-core has not been installed to ~/.m2 before, because Maven cannot find it among the selected projects. The fix is -am:

Terminal
mvn -pl shop-service -am verify

This builds shop-core and then shop-service, because -am pulled in the dependency. In the other direction, "I changed core, what could break?" is mvn -pl shop-core -amd verify, which builds core and every module that depends on it directly or indirectly. If a plugin option such as -Dtest= matches nothing in some of the selected modules, remember -Dsurefire.failIfNoSpecifiedTests=false from Running Tests with Surefire.

Inheritance versus aggregation

These two relationships are different, and the same root POM often plays both roles, which is why they get confused.

Aggregation is about building together. The aggregator lists modules in <modules>. The modules do not need to know the aggregator exists.

Inheritance is about sharing configuration. A child declares <parent> and takes its properties, dependencyManagement, plugin settings and so on. The parent does not need to know its children exist.

XML
<!-- shop-core/pom.xml -->
<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.example.shop</groupId>
    <artifactId>shop-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>
  <artifactId>shop-core</artifactId>
</project>

Here shop-core inherits groupId and version from the parent, so it only states its own artifactId. Because the parent is one folder up, the default relativePath of ../pom.xml finds it. You can build a project as an aggregator without it being anyone's parent, and you can have a shared parent POM in a separate repository that aggregates nothing. In the common case of one repository, the root POM is both.

What belongs in the parent? Things that should be the same everywhere: Java version, encoding, plugin versions, and dependencyManagement for library versions (Managing Versions). What belongs in a module? Only the dependencies it actually uses and anything specific to it.

Keep the module graph a simple layering: app depends on service, which depends on core. If you find yourself wanting core to depend on app, the boundary is wrong. A lean dependency direction is the main benefit of splitting into modules in the first place.

Stand-in: reactor ordering

The program below computes a build order from a map of module dependencies. It performs a depth-first walk in declaration order: before adding a module, it adds its dependencies. That gives the two properties from above: dependencies first, and declaration order otherwise. It also detects cycles. Real Maven also accounts for parents, plugins and build extensions when it builds its graph, but the sorting idea is the same.

Java Compute the reactor build order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Although shop-app is listed first, the build order starts with shop-core, then shop-service, then shop-app. shop-reports is listed second, but it comes last here: this simple walk finishes everything that shop-app needs before it moves on to the next listed module, and shop-reports is not one of those things. (Real Maven's tie-breaking among unconstrained modules can differ in detail; the guaranteed rule is only that dependencies come first.) In the last step we introduce a cycle, and the walk reports it instead of looping forever.

Stand-in: -pl and -am

The second program models module selection. Given the dependency graph, -pl picks a start set, -am adds everything the selection depends on (directly or indirectly), and -amd adds everything that depends on it. The result is then printed in reactor order.

Java Selecting modules with -pl, -am and -amd

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first line shows why plain -pl fails on a clean machine: shop-core is not part of the selection, so Maven would have to find it in the local repository. With -am the dependency is added and built first. The -amd line answers "what is affected by a change in core?", which here is every module.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In what order does the reactor build modules?

    Dependencies come first. Where nothing constrains the order, Maven keeps the declaration order. -T can run independent modules in parallel.
  2. 2. What does the -am option do?

    -am means also-make: build what the selected modules need. -amd (also-make-dependents) builds what needs them.
  3. 3. Module A depends on B and B depends on A. What happens?

    No valid build order exists. Extract the shared code into a third module.
  4. 4. Which statement about inheritance and aggregation is true?

    A POM can aggregate without being a parent, and be a parent without aggregating. In a single repository the root is usually both.
  5. 5. mvn -pl shop-service verify fails to find shop-core on a clean machine. What is the simplest fix?

    -am adds shop-core to the build so the reactor can resolve it. The other option is to run mvn install once so it is in the local repository.

Summary

  • A multi-module project has a root POM with <packaging>pom</packaging> and <modules>, plus one POM per module.
  • Modules depend on each other with normal dependencies; the reactor resolves them from the same build.
  • The reactor builds dependencies first, parents before children, and otherwise keeps the listed order; cycles are errors.
  • -pl selects modules, -am adds what they need, -amd adds what needs them, -rf resumes after a failure.
  • Aggregation (<modules>) and inheritance (<parent>) are separate ideas, usually both on the root POM.
  • Put shared versions and plugin settings in the parent; keep the module graph a clean one-way layering.

Next: Profiles and Environments