How to Create a executable JAR with Maven
1. The most important thing is to use the jar type,<
packaging
>jar</
packaging
>。当然不指定的话,默认Maven使用的就是jar。
2. Using Maven-dependency-plugin to create manually ( method one )
<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>
①. Goal is designated as copy-dependencies, which means that all dependencies are copied to the specified outputdirectory. In the example, create a Libs folder in the project build folder (usually the target folder).
②. Create an executable, classpath-aware jar using connections that are dependent on ① .
<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 manifest configuration, appended with a classpath prefixed with Libs, provides the fully qualified name of the main class information--main class.
Evaluation
Pros: The transparent process allows us to specify every step here
Cons: Do it manually, and the dependency is not in the final jar. means that the executable jar runs only if the Libs folder is accessible and visible to the jar.
2.2 Apache Maven Assembly Plugin
Apache Maven Assembly Plugin lets users summarize the output of a project into an executable package, including its dependencies, modules, site documents, and other files.
The main goal is single, which is used to create all the assemblies.
<plugin> <groupId>Org.apache.maven.plugins</groupId> <Artifactid>Maven-assembly-plugin</Artifactid> <executions> <Execution> <Phase>Package</Phase> <Goals> <goal>Single</goal> </Goals> <Configuration> <Archive> <Manifest> <MainClass>Org.baeldung.executable.ExecutableMavenJar</MainClass> </Manifest> </Archive> <Descriptorrefs> <Descriptorref>Jar-with-dependencies</Descriptorref> </Descriptorrefs> </Configuration> </Execution> </executions></plugin>
You also need to provide the main class information. The difference is that it automatically copies all the required dependencies into the jar file.
DESCRIPTORREF provides a name that is used to add to the project name.
Refer to Links:
1. Maven-assembly-plugin/usage
2. Pre-defined descriptor Files
maven-using MAVEN to build an executable jar