How to create an executable JAR with dependencies using Maven?
💻 coding

How to create an executable JAR with dependencies using Maven?

1 min read 149 words
1 min read
ShareWhatsAppPost on X
  • 1To create an executable JAR with dependencies, use the maven-assembly-plugin in your Maven project configuration.
  • 2Include the main class in the JAR manifest to specify the entry point for execution.
  • 3Run 'mvn clean compile assembly:single' to package your project, ensuring all dependencies are included.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To create an executable JAR with dependencies, use the maven-assembly-plugin in your Maven project configuration."

How to create an executable JAR with dependencies using Maven?

How can I package my project in a single executable JAR for distribution?

How can I make a Maven project package all dependency JARs into my output JAR?

The Solution for the following issue is as below:

<build>
 <plugins>
 <plugin>
 <artifactId>maven-assembly-plugin</artifactId>
 <configuration>
 <archive>
 <manifest>
 <mainClass>fully.qualified.MainClass</mainClass>
 </manifest>
 </archive>
 <descriptorRefs>
 <descriptorRef>jar-with-dependencies</descriptorRef>
 </descriptorRefs>
 </configuration>
 </plugin>
 </plugins>
</build>

and you run it with

mvn clean compile assembly:single

Compile goal should be added before assembly:single or otherwise the code on your own project is not included.

See more details in comments.

Commonly this goal is tied to a build phase to execute automatically. This ensures the JAR is built when executing mvn install or performing a deployment/release.

<plugin>
 <artifactId>maven-assembly-plugin</artifactId>
 <configuration>
 <archive>
 <manifest>
 <mainClass>fully.qualified.MainClass</mainClass>
 </manifest>
 </archive>
 <descriptorRefs>
 <descriptorRef>jar-with-dependencies</descriptorRef>
 </descriptorRefs>
 </configuration>
 <executions>
 <execution>
 <id>make-assembly</id> <!-- this is used for inheritance merges -->
 <phase>package</phase> <!-- bind to the packaging phase -->
 <goals>
 <goal>single</goal>
 </goals>
 </execution>
 </executions>
</plugin>

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 29 November 2018 · 1 min read · 149 words

Part of AskGif Blog · coding

You might also like