Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

maven - Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...