Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 41 ยท Packaging and Multi-module

Packaging: JAR, WAR and Executable Jars

Choose the right Maven packaging: jar, war and pom, the MANIFEST Main-Class entry, and how Shade, Assembly and the Spring Boot plugin build a runnable fat jar.

The last step of a successful build is a file you can hand to someone else. In Maven that file is decided by one element of the POM, <packaging>, and by the plugins bound to the package phase. A library becomes a .jar. A classic web application becomes a .war. A parent project that only organizes other modules becomes a .pom. And a command-line tool or a service usually needs one more step to become a single file you can start with java -jar.

This lesson explains the packaging types, what a JAR really is, why a normal jar cannot simply be run, and the three common ways to build an executable ("fat" or "uber") jar. The Maven commands and plugin settings are read-only here, because they need an installation. The runnable parts are Java stand-ins that use the JDK's own java.util.jar classes to build a manifest and a small jar in memory. They show what the files contain; they do not replace the plugins. This lesson builds on Lifecycles and Phases and Transitive Dependencies and Mediation.

The packaging types

The default packaging is jar, so a POM without <packaging> produces a jar. The value also selects which plugin goals are bound to which phases, as described in Plugins and Goals.

Packaging Output Used for
jar (default) app-1.0.jar Libraries and applications
war app-1.0.war Web applications for a servlet container
pom no file (just the POM) Parent POMs and aggregators
ear .ear Enterprise bundles, rare today
maven-plugin a plugin jar Maven plugins

For war, the maven-war-plugin assembles WEB-INF/classes, WEB-INF/lib and the static files from src/main/webapp. Since Servlet 3, a web.xml is optional, so modern projects set <failOnMissingWebXml>false</failOnMissingWebXml> in the plugin configuration. For pom, nothing is packaged: the POM itself is the artifact, which is exactly what a parent or a BOM needs.

What the package phase makes

jar Classes and resources in one archive.
war A web app for a servlet container.
pom Only the POM. For parents and aggregators.
1 / 2

What is inside a JAR

A JAR is an ordinary ZIP file with one convention: the entry META-INF/MANIFEST.MF, a text file of Name: value headers. Your compiled classes, from target/classes, sit in package folders, and the resources from src/main/resources are copied next to them. You can inspect a jar from the command line (read-only here):

Terminal
jar tf target/app-1.0.jar
unzip -p target/app-1.0.jar META-INF/MANIFEST.MF

The jar plugin writes a few headers automatically, such as Created-By and Build-Jdk-Spec. What it does not write by default is Main-Class, the header that tells java -jar which class contains main. Without it you get:

TEXT
no main manifest attribute, in app-1.0.jar

Add it through the jar plugin:

XML
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jar-plugin</artifactId>
  <version>3.4.2</version>
  <configuration>
    <archive>
      <manifest>
        <mainClass>com.example.app.Main</mainClass>
      </manifest>
    </archive>
  </configuration>
</plugin>

The dependency problem

Even with Main-Class set, java -jar target/app-1.0.jar fails with NoClassDefFoundError as soon as your code touches a library, because your jar contains only your classes. Dependencies are separate jars in ~/.m2, and java -jar does not know where they are. There are two straightforward fixes:

  1. Put the dependencies next to the jar and list them in the manifest Class-Path header. The jar plugin can write the header (addClasspath and classpathPrefix in the manifest element) and the dependency plugin can copy the jars into target/lib with its copy-dependencies goal. You then ship a folder.
  2. Build one file that contains everything: a fat jar.

Option 2 is what people usually want for services and tools, and Maven has three popular ways to get it.

Fat jar 1: the Shade plugin

The Shade plugin runs in the package phase, unpacks your classes and all dependency jars, and writes them into one flat jar:

XML
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <version>3.6.1</version>
  <executions>
    <execution>
      <phase>package</phase>
      <goals><goal>shade</goal></goals>
      <configuration>
        <transformers>
          <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
            <mainClass>com.example.app.Main</mainClass>
          </transformer>
          <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
        </transformers>
      </configuration>
    </execution>
  </executions>
</plugin>

Flattening creates a problem: two libraries may contain a file with the same path. Usually the first one wins and the second is silently dropped. That is harmless for a duplicated license file, but harmful for files that must be combined, such as META-INF/services/..., which Java's ServiceLoader uses to find implementations. The ServicesResourceTransformer merges those files instead of dropping one. Shade can also relocate packages (rewrite com.google.common to com.example.shaded.com.google.common), so your copy of a library cannot clash with a different version elsewhere on the classpath. Signed jars need care too, because merging breaks their signatures; Shade can filter the signature files out.

Fat jar 2: Spring Boot's repackage

Spring Boot does not flatten. Its Maven plugin runs repackage after the normal jar is built and creates an archive with a different layout: your classes under BOOT-INF/classes, dependency jars as nested jars under BOOT-INF/lib, and a small launcher class that the manifest names as Main-Class while your real class becomes Start-Class:

XML
<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

If the project inherits from spring-boot-starter-parent, the plugin version and the repackage execution are already configured, so the snippet above is all you write. Because the dependency jars stay intact, there are no file conflicts and no signature problems. The cost is that the layout is Spring Boot specific, and other tools cannot read it directly.

Fat jar 3: the Assembly plugin

The Assembly plugin builds archives from a descriptor: which files go where, in which format (jar, zip, tar.gz). It has a ready-made descriptor for the "everything in one jar" case:

XML
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-assembly-plugin</artifactId>
  <version>3.7.1</version>
  <configuration>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
    <archive>
      <manifest>
        <mainClass>com.example.app.Main</mainClass>
      </manifest>
    </archive>
  </configuration>
  <executions>
    <execution>
      <phase>package</phase>
      <goals><goal>single</goal></goals>
    </execution>
  </executions>
</plugin>

This produces an extra file, app-1.0-jar-with-dependencies.jar, next to the normal jar. Assembly shines when you need a distribution bundle (a zip with scripts, config and jars), less so for plain fat jars, where Shade offers more control.

Which should you choose?

  • A library: plain jar. Never publish a fat jar as a library; consumers would get your dependencies twice and lose version mediation.
  • A Spring Boot application: the Spring Boot plugin.
  • A plain Java tool or service: Shade, with the services transformer.
  • A zip or tar.gz distribution: Assembly.
  • A servlet-container deployment: war, with provided scope for the servlet API (see Dependency Scopes).

Whatever you pick, test the result: build, then run java -jar target/<file>.jar on a clean machine or in a clean folder.

Stand-in: building a manifest

Java's standard library contains the same manifest reader and writer that tools use. The program below builds a manifest, writes it to bytes and prints it exactly as it would appear inside a jar. Note two real rules it demonstrates: Manifest-Version must be present or the other headers are not written, and a header line longer than 72 bytes is wrapped, with continuation lines starting with a single space.

Java Build a MANIFEST.MF

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real tools add a few more headers (Created-By and Build-Jdk-Spec) and build the Class-Path value from the dependency list. The wrapping rule is why a long Class-Path looks odd in a manifest: it is still one logical header.

Stand-in: a thin jar versus a fat jar

The second program writes two jars in memory with JarOutputStream. The thin jar holds only the application. The fat jar also holds the entries from two library jars, merged the way Shade does it: when two entries share a path the first one wins, except for META-INF/services/ files, which are concatenated. It then reads the result back and lists the entries and the Main-Class.

Java Thin jar versus fat jar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The two LICENSE files collide and the second is dropped. The two service files are combined into one with both plugin class names, which is exactly the situation the ServicesResourceTransformer exists for. If the merge had just kept the first file, BPlugin would never be found at run time, and the bug would only show up in the fat jar, not during development.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Running java -jar app.jar prints 'no main manifest attribute'. What is missing?

    java -jar needs Main-Class to know where main is. Configure it in the jar plugin's manifest or through Shade or Spring Boot.
  2. 2. Which packaging should a parent POM that only lists modules use?

    Packaging pom produces no code artifact. The POM itself is the artifact, which is what parents, aggregators and BOMs need.
  3. 3. Why does Shade need the ServicesResourceTransformer?

    When files with the same path collide, the first one wins by default. Service files must be combined so ServiceLoader finds all implementations.
  4. 4. How does a Spring Boot executable jar store dependencies?

    Spring Boot keeps dependency jars intact and uses a launcher to read them, so there are no file conflicts.
  5. 5. Should you publish a fat jar as a library to Maven Central?

    A library should publish a plain jar and declare dependencies in its POM, so consumers' builds can mediate versions.

Summary

  • <packaging> selects the output and the default plugin bindings: jar (default), war, pom and a few others.
  • A JAR is a ZIP with META-INF/MANIFEST.MF; java -jar needs the Main-Class header.
  • A thin jar contains only your classes; dependencies must come from a Class-Path or from a fat jar.
  • Shade flattens dependencies (use the services transformer, consider relocation), Spring Boot nests them under BOOT-INF/lib, Assembly builds archives from descriptors such as jar-with-dependencies.
  • Libraries ship plain jars; applications may ship fat jars.
  • Always test the final file with java -jar in a clean folder.

Next: Multi-Module Builds and the Reactor