Search code examples
javamavenmaven-assembly-pluginmulti-modulemaven-module

How to assembly multiple executable JARs from a multi-module maven project


I have a multi-module project like this

foobar
 |
 +-- pom.xml
 |
 +-- common-lib/
 |       |
 |       +-- pom.xml
 |       +-- src/
 |
 +-- foo-app/
 |       |
 |       +-- pom.xml
 |       +-- src/
 |
 +-- bar-app/
 |       |
 |       +-- pom.xml
 |       +-- src/
 |
-+-

Both foo-app and bar-app depend on code in common-lib and also on dependencies in their own POMs.

Using mvn package I can build three light JARs.

What I want is two executable JARs, each with dependencies included, for:

  • foo-app
  • bar-app

How do I do this with maven?


In case anyone suggests it, due to clashes between the dependencies for foo-app and bar-app I cannot merge them into one single foobar-app.


Solution

  • Add maven assembly plugin to the pom.xml's which you want to create a executable jar with dependencies. Execute mvn package on aggregator pom.xml. This command will execute mvn package command on all the sub modules. The ones that have maven assembly plugin will generate executable jars with dependencies.

    In your case add this to foo-app and bar-app projects pom.xml. And configure your <mainClass>your.package.mainclass</mainClass> according to each projects main class.

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>your.package.mainclass</mainClass>
                        </manifest>
                    </archive>
    
                </configuration>
                <executions>
                    <execution>
                        <id>assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>