Search code examples
javamavenjarexecutable-jarmaven-jar-plugin

Maven exec works, but java -jar does not


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?


Solution

  • 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.