https://www.baeldung.com/executable-jar-with-maven
In this quick article we'll focus on packaging a Maven project into an executable Jar file.
Usually, when creating a jar file, we want to execute it easily, without using the IDE; to that end, we'll discuss the configuration and pros/cons of using each of these approaches for creating the executable.
In order to create an executable jar, we don't need any additional dependencies. We just need to create Maven Java project, and have at least one class with the main(…) method.
In our example, we created Java class named ExecutableMavenJar.
We also need to make sure that our pom.xml contains the the following elements:
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
The most important aspect here is the type – to create an executable jar, double check the configuration uses a jar type.
Now we can start using the various solutions.
Let's start with a manual approach – with the help of the maven-dependency-plugin.
First, we'll copy all required dependencies into the folder that we'll specify:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/libs
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
There are two important aspects to notice. First, we specify the goal copy-dependencies, which tells Maven to copy these dependencies into the specified outputDirectory.
In our case, we'll create a folder named libs, inside the project build directory (which is usually the target folder).
In the second step, we are going to create executable and class path aware jar, with the link to the dependencies copied in the first step:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>
org.baeldung.executable.ExecutableMavenJar
</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
The most important part of above-mentioned is the manifest configuration. We add a classpath, with all dependencies (folder libs/), and provide the information about the main class.