Maven is one of the most used tools for Java application development.
Maven packaging will create a Jar file without dependencies.
Maven provides other plugins using which we can generate the jar with all its dependencies which is usually called FatJar, which is used as an executable Jar file.
These Fat Jars are mostly useful to build executable jar file, for suppose, if we are developing a microservice, if we don’t create fat jar file, we need to all its dependencies in one folder, add this folder to the classpath, and start the microservice, for each time we need to do these steps in manually, but if we generate the fat jar as it includes all its dependencies, not needed to add to the classpath, we can directly run the command to start the microservices. The same will be applicable for docker images, as we can pass the single command to start the docker container.
Maven provides different ways to generate the Fat jar:
Maven Assembly Plugin:
Add the below Maven plugin in pom.xml file:
Note: if the project has no main class then we can omit the archive section.
descriptorRef is the name that will be appended the package name.
The phase is used to specify when this maven goal should execute, suggest to specify the package because when we invoke mvn package, these jar with all dependencies will also be generated.
The drawback of this plugin is some class with the same package is added to the classpath, this assembly plugin will have only class.
Relocating classes feature is not supporting in the above plugin.
Maven provides another plugin shade-plugin will have this feature if the duplicate package names are present we configure with alternate package names.
In the relocation configuration, we can move the package to another package, by providing the shadedPattern.
This plugin also supports, if some of the packages are not using in the application, we don’t need in the final fat jar, we can exclude those package in the exclude section, which will improve the class loading performance.
For suppose, if a jar file contains 10 packages, but we are using only one package, then instead of excluding 9 packages, include 1 package.
We can use includes tag similar excludes.
Review fat jar:
Execute the below command to observe the fat jar folder structure:
jar tf target\magellan-connector-msexchange-online-graph-cmis-1.0.0-SNAPSHOT-jar-with-dependencies.jar
Third-party libraries are also available to prepare fat jar like one-jar maven plugin etc.
In the current content we learned what is the fat jar, its uses, how to create fat jar file in different ways.