Wednesday, December 12, 2012

Creating a Fat Executable Jar with the maven Shade Plugin

So here's a quick walk through of a Maven project that will assemble into a runnable fat jar. A Simple Class with a 'public static main' will be our Main-Class.

The Main-Class


package org.seekay.main;

import com.sun.jersey.api.core.ApplicationAdapter;

public class TestMain {

public static void main(String[] args) {
for(int i=0; i< 100; i++) {
System.err.println("Line "+ i);
}
ApplicationAdapter adapter = new ApplicationAdapter(null);
}
}

I've chosen a class at random from the Jersey-Server jar to be our external dependency to ensure that the external code is being packaged correctly.


The Pom

Including the 'maven-shade-plugin will cause all the dependencies listed in the pom to be unpacked into  our fat jar.


<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>


package

shade



implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>org.seekay.main.TestMain</mainClass>






<finalName>${artifactId}-${version}</finalName>

</plugin>

To use a different main class, simply change the 'mainClass' attribute in the example above to be the fully qualified name of whichever class you'd like to use.

When you run 'maven clean install' your package will be built containing all the dependencies required by your project. Running 'java -jar UberJarTestProject-0.0.1-SNAPSHOT.jar' will invoke the main class and start the application. In our example a null pointer is thrown in the construction of the 'ApplicationAdapter' class, showing that it has been included.

Download Project


No comments: