Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 66 ยท Packaging and Deployment

Building and Running the Jar

Build an executable Spring Boot jar with Maven or Gradle, see what is inside it, use layered jars, start it with java -jar and speed up startup with CDS and AOT caches.

A Spring Boot application is delivered as a single file you start with java -jar. No application server to install, no WAR to drop into one: the web server (Tomcat by default) is inside the jar. That is the "executable jar", often called a fat jar because it carries every dependency with it. It is the unit that the next lessons put into containers and deploy.

This lesson shows how to build the jar with Maven or Gradle, what is actually inside it (and why it needs special loading code), how layered jars make container builds fast, how to run it with configuration from outside, and how to cut startup time with Class Data Sharing and the JVM's AOT cache. The commands are read-only (no build tool runs on this site); the TryIts build a miniature jar in memory and inspect it with the real java.util.jar API.

From source to running service

Build Maven or Gradle compiles and repackages.
One jar Your classes plus every dependency.
Run java -jar app.jar and it serves.

The same file runs on a laptop, a server and a container.

1 / 2

Building the jar

A project generated by Spring Initializr (see Creating a Project) already includes the Boot build plugin. Its job is repackaging: after the normal build produces a plain jar with only your classes, the plugin rewrites it into the executable layout.

With Maven:

Terminal
./mvnw clean package                 # runs tests, builds target/demo-0.0.1-SNAPSHOT.jar
./mvnw clean package -DskipTests     # skip tests (only when CI ran them already)

With Gradle:

Terminal
./gradlew clean bootJar              # builds build/libs/demo-0.0.1-SNAPSHOT.jar
./gradlew build                      # also runs tests (and builds the jar)

The relevant plugin configuration is short. In Maven it lives in pom.xml:

XML
<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <executions>
        <execution>
          <goals>
            <goal>build-info</goal>      <!-- writes META-INF/build-info.properties -->
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

In Gradle:

GROOVY
plugins {
    id 'java'
    id 'org.springframework.boot' version '4.0.0'
    id 'io.spring.dependency-management' version '1.1.7'
}

springBoot {
    buildInfo()          // writes META-INF/build-info.properties
}

The version numbers here are only examples; keep whatever Initializr generated for you. Once build-info is configured, a BuildProperties bean exists and Actuator's /actuator/info shows the application name, version and build time, so you can always ask a running instance what it is. Add the git commit id with a plugin such as git-commit-id and the same endpoint reports the commit.

Two build habits pay off. Run ./mvnw clean verify (or ./gradlew clean build) in CI so the artifact you deploy is the one that passed the tests, and build once, then promote that same jar through test, staging and production instead of rebuilding for each environment. Configuration differences belong outside the jar (Properties, YAML and Externalized Config). For reproducible builds (the same source gives a byte-identical jar), set project.build.outputTimestamp in Maven, or preserveFileTimestamps = false and reproducibleFileOrder = true on the Gradle archive tasks.

What is inside a fat jar

A normal Java classpath cannot load a jar inside a jar, so the repackaged file includes a small launcher that does it. The layout looks like this:

TEXT
demo-0.0.1-SNAPSHOT.jar
โ”œโ”€โ”€ META-INF/
โ”‚   โ”œโ”€โ”€ MANIFEST.MF
โ”‚   โ””โ”€โ”€ build-info.properties
โ”œโ”€โ”€ BOOT-INF/
โ”‚   โ”œโ”€โ”€ classes/              your compiled classes and application.yml
โ”‚   โ”œโ”€โ”€ lib/                  every dependency, as nested jars
โ”‚   โ”œโ”€โ”€ classpath.idx         the classpath order
โ”‚   โ””โ”€โ”€ layers.idx            which file belongs to which layer
โ””โ”€โ”€ org/springframework/boot/loader/   the launcher classes

and the manifest points the JVM to the launcher, which in turn knows where your own main is:

TEXT
Main-Class: org.springframework.boot.loader.launch.JarLauncher
Start-Class: com.example.demo.DemoApplication
Spring-Boot-Version: 4.0.0
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx
Spring-Boot-Layers-Index: BOOT-INF/layers.idx

java -jar runs Main-Class, the JarLauncher; it builds a class loader that can read the nested jars in BOOT-INF/lib (stored uncompressed, so they can be read directly) and then calls Start-Class, your main method. Nothing is unpacked to disk. For this reason java -cp demo.jar com.example.demo.DemoApplication does not work: the classes are under BOOT-INF/classes/, not at the root.

The first TryIt builds a miniature jar with the same structure in memory, then opens it again with the real JarInputStream the way tooling would, printing the manifest and the entries. What is real: the jar format and API, and the layout and manifest keys. What is the stand-in: the files are tiny placeholders, not compiled classes.

Java Build and inspect a mini 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.

You can open any real Boot jar the same way with jar tf demo.jar, and read the manifest with unzip -p demo.jar META-INF/MANIFEST.MF.

Layered jars: why the order matters

Think of how you deploy repeatedly: your own code changes on every commit, but the 150 dependency jars change a few times a month. If the container image contains the fat jar as one file, every code change creates a new multi-hundred-megabyte layer, and every deployment pushes and pulls all of it.

Boot's repackaged jar is layered by default. BOOT-INF/layers.idx assigns each file to a layer, ordered from least to most likely to change:

  1. dependencies: released third-party jars (rarely change).
  2. spring-boot-loader: the launcher classes.
  3. snapshot-dependencies: -SNAPSHOT jars, which can change more often.
  4. application: your own classes and resources (change on every build).

You can list and extract the layers with the jar's built-in tool mode (Boot 3.3 and later; older versions used -Djarmode=layertools):

Terminal
java -Djarmode=tools -jar demo.jar list-layers
java -Djarmode=tools -jar demo.jar extract --layers --destination extracted

A Dockerfile then copies each layer in its own COPY step, in that order. Docker caches steps whose input did not change, so after a code change only the small application layer is rebuilt and transferred. Containers: Dockerfile and Buildpacks puts this to work.

The second TryIt assigns files to layers by the same rules and simulates which layers a deployment must rebuild after an ordinary code change versus a dependency upgrade. Sizes are made up for the demonstration. What is real: the layering rules and the caching logic. What is the stand-in: the sizes, and no Docker.

Java Layers and what a code change rebuilds

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 numbers show the point: an ordinary code change ships a handful of kilobytes with layers, while a dependency upgrade (rare) legitimately ships the big layer.

Running the jar

Terminal
java -jar demo-0.0.1-SNAPSHOT.jar

The same jar behaves differently in different environments because configuration comes from outside. In increasing order of power: environment variables, system properties and command-line arguments (see Profiles and Environment-Specific Config):

Terminal
# command line argument (highest precedence of these)
java -jar demo.jar --server.port=9090 --spring.profiles.active=prod

# environment variables (relaxed binding: SERVER_PORT, SPRING_PROFILES_ACTIVE)
SERVER_PORT=9090 SPRING_PROFILES_ACTIVE=prod java -jar demo.jar

# JVM settings go before -jar
java -XX:MaxRAMPercentage=75 -Dspring.config.additional-location=file:/etc/demo/ -jar demo.jar

JVM options must come before -jar; everything after the jar name is passed to your application as arguments. Never put secrets on the command line, since other users on the machine can see process arguments; use environment variables or mounted files.

On a plain Linux server you would run the jar as a service, for example with a systemd unit:

INI
[Unit]
Description=Demo service
After=network.target

[Service]
User=demo
WorkingDirectory=/opt/demo
EnvironmentFile=/etc/demo/demo.env
ExecStart=/usr/bin/java -XX:MaxRAMPercentage=75 -jar /opt/demo/demo.jar
SuccessExitStatus=143
Restart=on-failure

[Install]
WantedBy=multi-user.target

SuccessExitStatus=143 treats the exit code produced by a normal SIGTERM shutdown (128 + 15) as success. Run under a non-root user, and keep the jar read-only for that user. Containers are the more common route today; they are the next lesson.

If you need to run the application without the nested-jar launcher, which helps startup and is what container images do, extract it first:

Terminal
java -Djarmode=tools -jar demo.jar extract --destination app
java -jar app/demo.jar

The extracted demo.jar lists its dependencies in the manifest classpath (lib/ next to it), so the JVM loads ordinary jars directly.

Faster startup with CDS and the AOT cache

Every start, the JVM loads, parses and verifies thousands of classes (the Spring ones, Hibernate, Tomcat, Jackson...). Class Data Sharing (CDS) stores that processed class metadata in an archive file so the next run maps it from disk instead of redoing the work. Boot supports it from the extracted layout:

Terminal
# 1. extract
java -Djarmode=tools -jar demo.jar extract --destination app

# 2. training run: start the app, create the archive and exit right after the context is refreshed
java -XX:ArchiveClassesAtExit=app/demo.jsa -Dspring.context.exit=onRefresh -jar app/demo.jar

# 3. production run uses the archive
java -XX:SharedArchiveFile=app/demo.jsa -jar app/demo.jar

On a recent JDK, the AOT cache goes further (class loading and linking, plus profile data the JIT can reuse): record and create it in one command, then run with it.

Terminal
java -XX:AOTCacheOutput=app/demo.aot -Dspring.context.exit=onRefresh -jar app/demo.jar
java -XX:AOTCache=app/demo.aot -jar app/demo.jar

Typical gains are tens of percent off startup time. Three rules: the archive is tied to the exact JVM and jar that created it (rebuild it in the build pipeline, not by hand), the training run must start the application with the same classpath it will use in production, and if the JVM cannot use the archive it falls back to normal startup, so it is safe to try. Measure startup before and after. For the largest cuts, a native image is the next step (Native Images with GraalVM), at the price of build time and limits.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can you not start a Boot fat jar with java -cp demo.jar com.example.demo.DemoApplication?

    The executable jar uses a special layout. java -jar starts JarLauncher, which builds a class loader for the nested jars and then calls your Start-Class.
  2. 2. What is the purpose of layered jars?

    Docker caches a layer when its input is unchanged. Putting stable dependencies first means ordinary code changes only touch the last, small layer.
  3. 3. Where must JVM options such as -XX:MaxRAMPercentage=75 go in the command line?

    Everything after the jar file name is passed to the application. JVM options belong before -jar.
  4. 4. What is the best practice for getting the same application to different environments?

    Build once and promote the same artifact. Externalized configuration changes behavior without changing the jar you tested.
  5. 5. What does a CDS or AOT cache archive improve, and what is its main restriction?

    The archive stores preprocessed class data so startup does less work, but it is only valid for the JVM version and classpath that created it, so create it in the build.

Summary

  • The Boot build plugin repackages your build into an executable jar (mvn package or ./gradlew bootJar); build once and promote the same artifact.
  • A fat jar keeps your classes in BOOT-INF/classes and dependencies as nested jars in BOOT-INF/lib; the manifest's Main-Class is the JarLauncher and Start-Class is your main.
  • Layered jars order dependencies, loader, snapshot dependencies and application, so container builds re-ship only what changed.
  • Run with java -jar; put JVM options before -jar and keep configuration and secrets outside the jar.
  • Extract the jar and use CDS or an AOT cache for faster startup; archives belong to one exact JVM and jar.

Next: Containers: Dockerfile and Buildpacks.