Saturday, October 25, 2014

Solving Java.lang.NoClassDefFoundError in Maven

Most developers find this error when they run executables in the terminal. Commonly these types of errors don't occur in Integrated Development Environments (IDE). NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.


Most of the time this error will occur because of the dependencies, because JVM doesn't know the class-path of our dependencies. This video explains how classpath is very important in Java.



<build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.1</version>
    <executions>
     <execution>
      <id>copy-dependencies</id>
      <phase>package</phase>
      <goals>
       <goal>copy-dependencies</goal>
      </goals>
      <configuration>
       <outputdirectory>${project.build.directory}/lib</outputdirectory>
       <overwritereleases>false</overwritereleases>
       <overwritesnapshots>false</overwritesnapshots>
       <overwriteifnewer>true</overwriteifnewer>
      </configuration>
     </execution>
    </executions>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
     <archive>
      <manifest>
       <addclasspath>true</addclasspath>
       <classpathprefix>lib/</classpathprefix>
       <mainclass>$ full qualified path to your class</mainclass>
      </manifest>
     </archive>
    </configuration>
   </plugin>
  </plugins>
 </build>


We can work this problem easily by copying all the dependencies into one folder and setting the class path into that folder. To answer that we have to change the pom file as following.

I hope this blog post will help to answer your problem.Please check keywords like 'groupId, ArtifactId' because my code snippet change those keywords.
Please don't copy and paste this code. Please try to understand and change your pom file, otherwise you will find more troubles.

3 comments:

  1. Thanks :)
    This post helped me to solve my problem.

    ReplyDelete
  2. Thanks ... This helped to solve one of my biggest problems, adding jars to the class path without modifying the manifest manually... thankuu so much...:)

    ReplyDelete