Creating an UberJAR for an application and its dependencies

suggest change

A common requirement for a Java application is that it can be deployed by copying a single file. For simple applications that depend only on the standard Java SE class libraries, this requirement is satisfied by creating a JAR file containing all of the (compiled) application classes.

Things are not so straightforward if the application depends on third-party libraries. If you simply put dependency JAR files inside an application JAR, the standard Java class loader will not be able to find the library classes, and your application will not start. Instead, you need to create a single JAR file that contains the application classes and associated resources together with the dependency classes and resources. These need to be organized as a single namespace for the classloader to search.

Such a JAR file is often called an UberJAR.

Creating an UberJAR using the "jar" command

The procedure for creating an UberJAR is straight-forward. (I will use Linux commands for simplicity. The commands should be identical for Mac OS, and similar for Windows.)

  1. Create a temporary directory, and change directory to it.

    $ mkdir tempDir
    $ cd tempDir
    
  2. For each dependency JAR, use jar to unpack it into the temporary directory, in the reverse of classpath order. The last unpacked JAR wins when paths collide, so unpack the first classpath entry last.

    $ jar -xf <path/to/file.jar>
    

    Doing this for multiple JAR files overlays their contents. A later JAR overwrites an earlier META-INF/MANIFEST.MF.

  3. Copy the application classes from the build tree into the temporary directory.

    $ cp -r path/to/classes .
    
  4. Create the UberJAR from the contents of the temporary directory:

    $ jar -cf ../myApplication.jar .
    

    If you are creating an executable JAR, include a MANIFEST.MF that sets Main-Class. Put that manifest in the temporary directory before this command, or pass it with jar -cfm.

Creating an UberJAR using Maven

If your project is built using Maven, you can get it to create an UberJAR using either the "maven-assembly" or "maven-shade" plugins. See the Maven Assembly topic (in the Maven documentation) for details.

The advantages and drawbacks of UberJARs

Some advantages of UberJARs are self-evident:

In addition, UberJAR tools can exclude library classes that appear unused. That exclusion is typically done by static analysis. If the application uses reflection, annotation processing, or similar techniques, classes can be excluded incorrectly.

UberJARs also have some disadvantages:


1 - Some open source library licenses allow you to use the library only if the end user can replace one version of the library with another. UberJARs can make that replacement difficult.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents