Reputation: 1059
I have simple maven project with only one dependency. I can install it and run it command-line via Exec Maven Plugin:
mvn exec:java -D"exec.mainClass"="com.MyClass"
After packaging maven generates a .jar file in my directory. With a help of Maven JAR Plugin I made its manifest to know my main
method class. It looks like:
...
Created-By: Apache Maven 3.3.1
Build-Jdk: 1.8.0_66
Main-Class: com.MyClass
Now I want to run this .jar file like regular java executable using java
command, but after doing the following:
java -jar myFile.jar
it gives an error java.lang.NoClassDefFoundError
concerning my only dependency.
How can I make maven to add all dependencies into my executable jar file?
Upvotes: 1
Views: 2010
Reputation: 6297
One way to achieve this is using Apache Maven Shade Plugin:
This plugin provides the capability to package the artifact in an uber-jar, including its dependencies and to shade - i.e. rename - the packages of some of the dependencies.
This plugin has some advantages for large project with many dependencies. This is explained here: Difference between maven plugins ( assembly-plugins , jar-plugins , shaded-plugins)
In my project I use it with this configuration:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.xxx.tools.imagedump.ImageDumpLauncher</mainClass>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/spring.schemas</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
Upvotes: 2
Reputation: 4472
You could use the Apache Maven Assembly Plugin, in order to create a jar with all its dependencies, so your pom.xml should be like the following:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>mypackage.myclass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
I hope it helps you, bye.
Upvotes: 1