小能豆

How can I create an executable/runnable JAR with dependencies using Maven?

java

I want to 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?


阅读 159

收藏
2023-12-26

共1个答案

小能豆

To create a single executable JAR file that includes all the dependencies for a Maven project, you can use the Maven Assembly Plugin or the Maven Shade Plugin. Both plugins allow you to create an “uber-JAR” or “fat JAR” that contains both your project code and its dependencies.

Maven Assembly Plugin:

  1. Add the Maven Assembly Plugin to your pom.xml file:

<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.3.0</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build>

  1. Run the following Maven command:

mvn clean package

This will generate an executable JAR with the suffix -jar-with-dependencies in the target directory.

Maven Shade Plugin:

  1. Add the Maven Shade Plugin to your pom.xml file:

<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.2.4</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>your.main.class</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build>

Replace your.main.class with the fully qualified name of your main class.

  1. Run the following Maven command:

mvn clean package

This will generate an executable JAR in the target directory.

Choose the plugin that best fits your needs. The generated JAR will include all dependencies, making it a standalone executable.

2023-12-26