Caused by: java.lang.ClassNotFoundException: org.s

2019-01-26 20:15发布

问题:

some problems with java and slf4j Made project using idea and it is ok. But in case I try to make jar with gradle I have some problems.

build.gradle

group 'test.test'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'org.slf4j:slf4j-api:1.7.20'
    compile 'ch.qos.logback:logback-classic:1.1.7'

}


jar {
    manifest {
        attributes 'Main-Class': 'Test'
    }
}

Test.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Test {
    private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);

    public static void main(String[] args) {
        LOGGER.info("info");
    }
}

Terminal:

gradle build
java -jar target/HttpServer-1.0-SNAPSHOT.jar 

Output:

Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
        at HttpServerHH.Main.<clinit>(Main.java:15)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more

I tried to use gradle/maven (mvn package) the same problem. Some reasons it cannot find Logger and LoggerFactory in classpath.

回答1:

Thanks Michael for remembering about fat jar. After your comment tried to google: "gradle build fat jar" and after it modified my build.gradle

jar {
    from {
        configurations.compile.collect {
            it.isDirectory() ? it : zipTree(it)
        }
    }
    manifest {
        attributes 'Main-Class': 'Test'
    }
}


回答2:

JVM cannot find dependencies on classpath because they're not on classpath obviously. By default Gradle and Maven add just your classes to a jar and you have to specify paths to the dependencies manually with the -cp argument. If you want to build a fat jar you can use ShadowJar with Gradle and Shade with Maven.



回答3:

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
    compile 'ch.qos.logback:logback-core:1.1.6'
    compile 'ch.qos.logback:logback-classic:1.1.6'
    compile 'org.slf4j:slf4j-api:1.7.18'
}