Search code examples
javamavensnakeyaml

NoClassDefError: SnakeYAML, with Maven


I'm having a runtime issue occurring with SnakeYAML and maven. For some reason, I'm getting a java.lang.NoClassDefFoundError with Yaml when I run my .jar.

Here is the stack trace:

Exception in thread "main" java.lang.NoClassDefFoundError: org/yaml/snakeyaml/Yaml
    at my.package.TimberServer.loadConfiguration(TimberServer.java:56)
    at my.package.TimberServer.<init>(TimberServer.java:38)
    at my.package.Main.main(Main.java:17)
Caused by: java.lang.ClassNotFoundException: org.yaml.snakeyaml.Yaml
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 3 more

Here is the section in my pom.xml in which I declare the dependency (link to central repository):

    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.14</version>
    </dependency>

I don't declare any repository for it.

Here is the code that calls (and imports) the Yaml class:

import org.yaml.snakeyaml.Yaml;
// everything else is imported, yes

public class TimberServer {

    public void loadConfiguration() throws IOException {
        Yaml yaml = new Yaml(); // Error occurs HERE.
        Map config = (Map) yaml.load(FileUtils.readFileToString(this.config));
        Map<String, String> serverConfig = (Map<String, String>) config.get("server");
    }
}

I get no errors when compiling with maven, which is the most confusing part to me - does Java not check for existent classes? I'm programming with an IDE (IntelliJ), which does not give any errors or warnings with the lines of code.


Solution

  • After help from @Seelenvirtuose in the comments, I came across this solution:

    I was running mvn package alone - with no dependency plugin, which I learned is a necessity for packaging. However, in my specific case, the Uber jar plugin did not want to work right and I had to use the Assembly plugin.

    Note: the resultant .jar from the Assembly plugin will be named target/yourProject-jar-with-dependencies.jar. I overlooked this.