Build executable jar using Maven Shade Plugin

Maven Shade Plugin is a Maven plugin that allows us to build uber-jars. In a nutshell, uber-jar are .jar files that, besides containing the source code of the application, also contain the dependencies that the application is using. From there, it helps us to build Java applications that can run standalone.

For example, I have a Maven project with a simple main class, when running, it will display the words “Hello from Huong Dan Java” as follows:

In this example, I have used the commons-lang3 library to capitalize the first letter of this text.

Result when running the application:

Build executable jar using Maven Shade Plugin

Now, I will declare to use Maven Shade Plugin to build this application that can run standalone:

Here, I have configured to run the Maven Shade Plugin when we build the application with the “package” phase. At that time, Maven Shade Plugin will run the goal “shade” to package our source code with the dependencies it is using. I also configure resources transformer for Maven Shade Plugin with ManifestResourceTransformer that allows us to define a mainClass in the META-INF/MANIFEST.MF file of the jar file, making the jar file after building, can run standalone.

Well, there is a note that Maven Shade Plugin only works with Java from version 7 and up! You can configure your Maven project as follows to be able to use the Maven Shade Plugin:

This is because I use Java 8.

Now, if you run Maven build with the goal “clean package” for this project, then open Terminal on Linux/macOS or Console on Windows, go to the project’s target directory, run the command: “java -jar maven-shade -plugin-example-0.0.1-SNAPSHOT.jar”, you will see the following results:

Build executable jar using Maven Shade Plugin

As you can see, although I use the commons-lang3 library for my application, I don’t need to declare the classpath to this library at all. That’s because this library is already included in the maven-shade-plugin-example-0.0.1-SNAPSHOT.jar file!

You can also define some other information in the META-INF/MANIFEST.MF file inside the jar file, by configuring the Maven Shade Plugin as follows:

At this point, rebuild the project, extract the jar file, you will see the META-INF/MANIFEST.MF file with similar content as follows:

Add Comment