Build Executable JAR in Java
A JAR file packages your compiled classes and resources into one file. To build executable JAR in Java projects, the JAR also needs a Main-Class entry in its manifest and a way to find its libraries, so that java -jar app.jar starts the program on any machine.
This lesson builds plain, executable, thin and fat JARs with both Maven and Gradle, shows how to inspect what ends up inside, and explains when to use each kind. It ends with a release-ready fat JAR that reports its own version. To create a JAR by hand with the jar tool, see JAR File in Java.
Types of JAR Files for Java Applications
| JAR type | Contains | Run with | Best for |
|---|---|---|---|
| Plain JAR | Your classes only, no Main-Class | java -cp app.jar:libs/* Main | Libraries used by other projects |
| Executable JAR | Your classes + Main-Class | java -jar app.jar | Apps with no external libraries |
Thin JAR + lib/ | Your classes + Main-Class + Class-Path to lib/*.jar | java -jar app.jar (with lib/ next to it) | Apps where libraries are updated separately |
| Fat (uber) JAR | Your classes + every runtime library, unpacked | java -jar app-all.jar | Command-line tools and services shipped as one file |
All examples use this small app from Gradle Dependencies: it uses Gson at compile time and the H2 database driver at run time.
student-export/
└── src/main/java/com/gocourse/export/
├── App.java <- main class, creates an H2 table and prints JSON
├── Student.java <- record
└── StudentExporter.java <- reads rows with JDBC, writes JSON with Gson
How it works:
- A JAR is a ZIP file.
META-INF/MANIFEST.MFinside it holds settings such asMain-ClassandClass-Path. java -jarignores-cpand theCLASSPATHvariable. Everything the app needs must be reachable from the manifest, which is why libraries are the hard part.
Build a Plain JAR With Maven and Gradle
Both tools create a plain JAR as part of their normal build.
# Maven
mvn -q package
jar tf target/student-export-1.0.0.jar
# Gradle
./gradlew jar -q
jar tf build/libs/student-export-1.0.0.jar
Output (both tools list the same entries):
META-INF/
META-INF/MANIFEST.MF
com/
com/gocourse/
com/gocourse/export/
com/gocourse/export/App.class
com/gocourse/export/Student.class
com/gocourse/export/StudentExporter.class
Try to run it:
java -jar target/student-export-1.0.0.jar
no main manifest attribute, in target/student-export-1.0.0.jar
How it works:
jar tflists the files inside a JAR without extracting them.- The JAR has no
Main-Classin its manifest, sojava -jardoes not know which class to start. - Gson and H2 are not inside. Even with a
Main-Class, the app would fail withNoClassDefFoundError: com/google/gson/GsonBuilder.
Add Main-Class to the Manifest
Maven: Configure the JAR Plugin
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<archive>
<manifest>
<mainClass>com.gocourse.export.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
Gradle: Configure the jar Task
tasks.jar {
manifest {
attributes("Main-Class" to "com.gocourse.export.App")
}
}
mvn -q package
unzip -p target/student-export-1.0.0.jar META-INF/MANIFEST.MF
java -jar target/student-export-1.0.0.jar
Output (shortened):
Manifest-Version: 1.0
Created-By: Maven JAR Plugin 3.5.0
Build-Jdk-Spec: 25
Main-Class: com.gocourse.export.App
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/GsonBuilder
at com.gocourse.export.StudentExporter.<init>(StudentExporter.java:14)
at com.gocourse.export.App.main(App.java:18)
Caused by: java.lang.ClassNotFoundException: com.google.gson.GsonBuilder
How it works:
unzip -pprints one file from the JAR. On Windows, usejar xfto extract it, or open the JAR with any ZIP tool.Main-Classnow startsApp, sojava -jargets further. The app fails at the first line that needs Gson.- An executable JAR with only
Main-Classis enough only when the app uses nothing beyond the JDK. The next two sections add the libraries.
Build a Thin JAR With a lib Folder
A thin JAR keeps libraries as separate files in a lib/ folder and lists them in the manifest's Class-Path.
Maven: addClasspath and copy-dependencies
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<archive>
<manifest>
<mainClass>com.gocourse.export.App</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.11.0</version>
<executions>
<execution>
<id>copy-libs</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
mvn -q package
unzip -p target/student-export-1.0.0.jar META-INF/MANIFEST.MF | grep -A1 Class-Path
ls target/lib
java -jar target/student-export-1.0.0.jar
Output:
Class-Path: lib/gson-2.13.2.jar lib/error_prone_annotations-2.41.0.jar l
ib/h2-2.4.240.jar
error_prone_annotations-2.41.0.jar
gson-2.13.2.jar
h2-2.4.240.jar
[
{
"name": "Asha",
"course": "Java",
"marks": 92
},
{
"name": "Ravi",
"course": "Python",
"marks": 78
}
]
How it works:
addClasspathwrites every runtime dependency intoClass-Path, andclasspathPrefixputslib/in front of each name. Manifest lines are wrapped at 72 characters, which is whylib/h2is split across two lines.copy-dependenciescopies the same JARs intotarget/libduringpackage.includeScope=runtimecopiescompileandruntimelibraries but not test ones.- Paths in
Class-Pathare relative to the JAR. Shipstudent-export-1.0.0.jarand thelib/folder together.
Gradle: installDist From the application Plugin
The application plugin already builds a thin distribution with start scripts:
./gradlew installDist -q
ls build/install/student-export/lib
build/install/student-export/bin/student-export
Output (shortened):
error_prone_annotations-2.41.0.jar
gson-2.13.2.jar
h2-2.4.240.jar
student-export-1.0.0.jar
[
{
"name": "Asha",
...
How it works:
installDistcopies your JAR and all runtime libraries intobuild/install/<name>/liband writes abin/script for Linux/macOS and a.batfile for Windows.- The script builds the classpath and calls
javafor you, so noClass-Pathmanifest entry is needed../gradlew distZippacks the same folder into a ZIP for release.
Build a Fat JAR With Maven Shade or Gradle
A fat JAR unpacks every runtime library into one JAR, so there is only one file to copy and run.
Maven: maven-shade-plugin
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.2</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>all</shadedClassifierName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.gocourse.export.App</mainClass>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>module-info.class</exclude>
<exclude>META-INF/versions/*/module-info.class</exclude>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
Gradle: a Jar Task That Includes the Runtime Classpath
tasks.register<Jar>("fatJar") {
group = "build"
description = "Builds a runnable JAR that contains all runtime dependencies."
archiveClassifier = "all"
manifest {
attributes("Main-Class" to "com.gocourse.export.App")
}
from(sourceSets.main.get().output) // your classes and resources
dependsOn(configurations.runtimeClasspath)
from({
configurations.runtimeClasspath.get()
.filter { it.name.endsWith(".jar") }
.map { zipTree(it) } // unpack each library
})
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
exclude("module-info.class", "META-INF/versions/*/module-info.class",
"META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
}
mvn -q package && java -jar target/student-export-1.0.0-all.jar
./gradlew fatJar -q && java -jar build/libs/student-export-1.0.0-all.jar
Output (printed once by each tool):
[
{
"name": "Asha",
"course": "Java",
"marks": 92
},
{
"name": "Ravi",
"course": "Python",
"marks": 78
}
]
How it works:
- Both builds keep the plain JAR and add a second file with the classifier
all, so library users still get the thin JAR. ServicesResourceTransformermergesMETA-INF/servicesfiles. JDBC drivers register themselves there, so dropping or overwriting those files would breakDriverManager.- In Gradle,
zipTreeopens each library JAR so its classes are copied in.duplicatesStrategy = EXCLUDEkeeps the first copy of files that several libraries share, such asMETA-INF/MANIFEST.MF. - The excludes remove module descriptors and signature files from libraries. A merged JAR cannot hold several
module-info.classfiles, and old signatures no longer match.
Note: If two libraries ship different
META-INF/servicesfiles with the same name, the Gradle task above keeps only the first. In that case, use the Shadow plugin (com.gradleup.shadow), which merges service files like Maven Shade does.
Inspect and Run an Executable JAR
Before you release a JAR, check its manifest, its contents and the Java version it needs.
| Command | Purpose |
|---|---|
jar tf app.jar | List all entries |
unzip -p app.jar META-INF/MANIFEST.MF | Print the manifest |
jar --describe-module --file app.jar | Show module information, if any |
javap -v -cp app.jar com.example.Main | grep major | Show the class file version |
java -jar app.jar arg1 arg2 | Run with arguments |
javap -v -cp target/student-export-1.0.0-all.jar com.gocourse.export.App | grep major
Output:
major version: 69
How it works:
- Class file version 69 means Java 25 (version = Java release + 44). A user with Java 21 sees
UnsupportedClassVersionErrorand must upgrade, or you must lowerreleasein the build. - Arguments after the JAR name go to
main(String[] args); JVM options such as-Xmx512mgo before-jar.
Real-World Example: Build Executable JAR in Java for a Release
This release build creates student-export-1.2.0-all.jar, a fat JAR whose manifest also records the version. The app reads that version at run time, so the printed version always matches the build. The Gradle build is shown in full, followed by the matching Maven settings.
// build.gradle.kts
plugins {
application
}
version = "1.2.0"
repositories { mavenCentral() }
java {
toolchain { languageVersion = JavaLanguageVersion.of(25) }
}
dependencies {
implementation("com.google.code.gson:gson:2.13.2")
runtimeOnly("com.h2database:h2:2.4.240")
}
val mainClassName = "com.gocourse.export.App"
application {
mainClass = mainClassName
}
tasks.register<Jar>("fatJar") {
group = "build"
description = "Builds the release JAR with all runtime dependencies."
archiveClassifier = "all"
manifest {
attributes(
"Main-Class" to mainClassName,
"Implementation-Title" to project.name,
"Implementation-Version" to project.version)
}
from(sourceSets.main.get().output)
dependsOn(configurations.runtimeClasspath)
from({
configurations.runtimeClasspath.get()
.filter { it.name.endsWith(".jar") }
.map { zipTree(it) }
})
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
exclude("module-info.class", "META-INF/versions/*/module-info.class",
"META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA")
}
tasks.build {
dependsOn("fatJar") // every build also produces the release JAR
}
// src/main/java/com/gocourse/export/App.java
package com.gocourse.export;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class App {
public static void main(String[] args) throws Exception {
Package appPackage = App.class.getPackage();
String title = appPackage.getImplementationTitle();
String version = appPackage.getImplementationVersion();
System.out.println(title + " " + (version != null ? version : "(development build)"));
String jdbcUrl = "jdbc:h2:mem:school;DB_CLOSE_DELAY=-1";
try (Connection connection = DriverManager.getConnection(jdbcUrl);
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE students (name VARCHAR(50), course VARCHAR(50), marks INT)");
statement.execute("INSERT INTO students VALUES ('Ravi', 'Python', 78), ('Asha', 'Java', 92)");
}
System.out.println(new StudentExporter().exportJson(jdbcUrl));
}
}
Student.java and StudentExporter.java are unchanged from Gradle Dependencies.
The matching Maven settings add the same manifest entries to the Shade transformer:
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.gocourse.export.App</mainClass>
<manifestEntries>
<Implementation-Title>${project.artifactId}</Implementation-Title>
<Implementation-Version>${project.version}</Implementation-Version>
</manifestEntries>
</transformer>
Build the release and run it from a clean folder, as a user would:
./gradlew build -q
mkdir -p /tmp/release && cp build/libs/student-export-1.2.0-all.jar /tmp/release/
cd /tmp/release
java -jar student-export-1.2.0-all.jar
Output:
student-export 1.2.0
[
{
"name": "Asha",
"course": "Java",
"marks": 92
},
{
"name": "Ravi",
"course": "Python",
"marks": 78
}
]
During development, ./gradlew run prints null (development build) on the first line, because classes loaded from build/classes have no manifest.
How it works:
- One source of truth.
version = "1.2.0"names the file and fillsImplementation-Version.Package.getImplementationVersion()reads it back from the manifest of the JAR the class was loaded from. - Everything inside. The
fatJartask unpacks Gson, its annotations and H2 next to your classes, so the copied JAR runs alone in/tmp/releasewith nolib/folder. - Driver discovery still works. H2 registers itself through
META-INF/services/java.sql.Driver. Only H2 ships that file here, so the simple Gradle task keeps it intact; the Maven build usesServicesResourceTransformerto be safe in every case. - Part of every build.
tasks.build { dependsOn("fatJar") }means CI only needs to run./gradlew buildand uploadbuild/libs/*-all.jar. - Clean manifests. Excluding library signatures and module descriptors avoids
SecurityException: Invalid signature file digestand module errors at startup.
The plugins that produce these JARs on the Maven side are covered in Maven Plugins, and the tasks behind them on the Gradle side in Gradle Build.