Search code examples
mavenparent

Maven build all in order


I have a project where all of my projects have a parent pom defined like this:

<parent>
    <groupId>MyProject</groupId>
    <artifactId>MyApp</artifactId>
    <version>1.0</version>
</parent>

However, this parent pom does NOT specify the modules in a modules element.

So when I run the mvn install -f parent/pom.xml command it doesn't do anything.

Is there some OTHER way I can build the entire project In Order so that all of the poms are built?

By "in order" i mean "built in order of dependency". Because several projects depend on others, we can't just build each project alphabetically.


Solution

  • If you have a reactor pom (a pom with the <modules> element, and <packaging> defined as pom) then the modules will be built in dependency order. This ordering happens regardless of the order the modules are specified in the pom.

    There's a few ways to approach this:

    Option 1

    Your reactor pom doesn't need to be the same pom as your parent pom. So you could have:

    project/pom.xml          # Reactor pom with <modules> element
    project/parent/pom.xml   # Parent pom
    project/module-a/pom.xml # Some module 'a'
    project/module-b/pom.xml # Some module 'b'
    

    In this case, the reactor pom contains:

    <modules>
      <module>parent</module>
      <module>module-a</module>
      <module>module-b</module>
    </modules>
    

    Running mvn install at the top level will build your parent pom, and the two modules in dependency order.

    Option 2

    Move your parent pom up a directory, and use it as both a parent pom and a reactor pom, so your project looks like this

    project/pom.xml          # Parent/Reactor pom with <modules> element
    project/module-a/pom.xml # Some module 'a'
    project/module-b/pom.xml # Some module 'b'
    

    The modules section in it would look like this

    <modules>
      <module>module-a</module>
      <module>module-b</module>
    </modules>
    

    Again, running mvn install at the top level will build your parent pom, and the two modules in dependency order.

    Option 3

    Leave your parent pom where it is, and add a modules section:

    <modules>
      <module>../module-a</module>
      <module>../module-b</module>
    </modules>
    

    In this case, running mvn install -f parent/pom.xml will build the parent pom, and the two modules in dependency order.

    Conclusion

    I normally use Option 2. It's the pattern that's most used in maven itself, and I try to avoid straying too far from the 'beaten path', which is widely understood and tested.

    For more information, see the Guide to Working with Multiple Modules.