How can I create an executable/runnable JAR with dependencies using Maven?
To create an executable JAR with dependencies using Maven, you can use the maven-assembly-plugin
. This plugin allows you to package your project and its dependencies into a single JAR file.
To use the maven-assembly-plugin
, you will need to add it to your pom.xml
file and configure it to create an executable JAR. Here's an example of how to do this:
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<archive>
<manifest>
<mainClass>com.example.Main</mainClass>
</manifest>
</archive>
<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>
This configuration creates an executable JAR file with the name ${project.artifactId}-${project.version}-jar-with-dependencies.jar
that includes all of the project's dependencies. The mainClass
element specifies the fully qualified name of the main class that should be used to execute the JAR file.
To create the executable JAR, run the following command:
mvn package
This will create the JAR file in the target
directory. You can then run the JAR file using the java -jar
command, like this:
java -jar target/${project.artifactId}-${project.version}-jar-with-dependencies.jar
Note that this configuration will include all of the project's dependencies in the JAR file. If you only want to include certain dependencies, you can specify them in the <dependencies>
element of the <configuration>
block. For example:
<configuration>
<archive>
<manifest>
<mainClass>com.example.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>dependency1</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>dependency2</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</configuration>
This configuration will include only the dependency1
and dependency2
dependencies in the JAR file.