Search code examples
javaspringmavenjar

Building a Maven multi module project as single jar


I've developed a simple Maven multi-module project that is fully functional. The goal in this project is to package two jars (from module a and module b) into a single fully functional jar containing both applications. The project can be launched through either MainA or MainB. Here's the project: Maven multi module project

While the project runs smoothly within the IDE (either running MainA, MainB, or the final jar), I encounter an issue when attempting to execute the final .jar outside the project directory. Upon running mvn clean install in the root project folder, the final jar (possibly referred to as an uber jar, not sure though) is generated in the a module's target folder with the name a-1.0-SNAPSHOT.jar. However, when I try to run this jar (java -jar a-1.0-SNAPSHOT.jar) outside the IDE, the execution fails.

I suspect that the dependencies are not being properly included in the final jar, despite using the maven-assembly-plugin. I've reviewed my configurations but haven't been able to identify the cause of this issue.

Any insights or suggestions on resolving this issue would be greatly appreciated.


Solution

  • For my surprise, it worked with maven-shade-plugin!

    Just had to remove all plugins from sub-modules, and in the parent module I added it:

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <id>shade-jar-with-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Main-Class>login.Main</Main-Class>
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    

    And there you have it. Multi module maven project with Spring boot with multiple jars (from different entry Main classes) self-contained in a single jar. Soon I'll be updating the project with the fix.