引起:java.lang.ClassNotFoundException:org.slf4j.LoggerFactory

时间:2016-04-02 18:53:10

标签: java maven gradle jar slf4j

java和slf4j的一些问题 使用想法制作项目,没关系。但是如果我尝试用gradle制作jar,我会遇到一些问题。

的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");
    }
}

终端:

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

输出:

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
我尝试使用gradle / maven(mvn包)同样的问题。有些原因它无法在classpath中找到Logger和LoggerFactory。

3 个答案:

答案 0 :(得分:3)

感谢Michael记得胖罐子。在您的评论尝试谷歌之后:&#34; gradle build fat jar&#34;并在修改了我的build.gradle

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

答案 1 :(得分:2)

JVM无法在类路径上找到依赖关系,因为它们显然不在类路径上。默认情况下,Gradle和Maven只将您的类添加到jar中,您必须使用-cp参数手动指定依赖项的路径。如果你想构建一个胖罐,你可以使用Gradle ShadowJar和Maven Shade

答案 2 :(得分:1)

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