Issue
Hello guys I am new to Maven and I am trying to integrate slf4j in a maven project Here is my pom.xml file
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.9</version>
</dependency>
And I have these two lines in my main function
Logger logger = LoggerFactory.getLogger(App.class);
logger.info("Hello World");
Project is compiled and packaged successfully but when I try to run it
through
java -cp target/maven-1.0-SNAPSHOT.jar com.goutam.maven.App
The following Exception is thrown
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at com.goutam.maven.App.main(App.java:11)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
Solution
I don't like the idea of building fat jars, as we loose some flexibilities in this approach.
Rather would advocate for copy-dependencies plugin in maven.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>install</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>
Coupling it along with maven-jar-plugin. Read this for details.
Assuming the third party dependencies are copied into target/lib folder.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<archive>
<manifest>
<mainClass>main class</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
Answered By - Himanshu Bhardwaj
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)