运行时Gradle Uber(Fat)Jar和java.lang.NoClassDefFoundError

时间:2018-02-07 19:39:03

标签: java gradle jar build.gradle uberjar

我正在尝试使用Gradle创建一个UberJar文件。

要构建并运行jar文件,我执行命令 ./gradlew clean build java -jar build/libs/jLocalCoin-0.2.jar

我得到了例外

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/primitives/Longs
    // ... rest of stacktrace
    at im.djm.zMain.Main03.main(Main03.java:13)
Caused by: java.lang.ClassNotFoundException: com.google.common.primitives.Longs
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 8 more

我不明白例外的原因是什么?
我明白Guava库不是jar的一部分,但为什么呢?

在这个questio中,在接受的答案中,jar文件的创建方式与我尝试的方式相同。

这是build.grade

apply plugin: 'java'
apply plugin: 'java-library'
apply plugin: 'application'

mainClassName = 'im.djm.zMain.Main03'

archivesBaseName = 'jLocalCoin'
version = "0.2"

run {
    standardInput = System.in
}

repositories {
    jcenter()
}

dependencies {
    implementation 'com.google.guava:guava:24.0-jre'

    testImplementation 'junit:junit:4.12'

    testCompile 'org.assertj:assertj-core:3.8.0'
}

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

1 个答案:

答案 0 :(得分:1)

您创建的jar可能没有番石榴。当您的项目在类路径中没有所需的运行时依赖时,会发生NoClassDefFoundError。我检查的教程以这种方式创建了fatJar,

task fatJar(type: Jar) {
   baseName = project.name + '-all'
   manifest {
        attributes 'Implementation-Title': 'Gradle Jar File Example',
            'Implementation-Version': version,
            'Main-Class': 'com.mkyong.DateUtils'
    }
   from { configurations.compile.collect { it.isDirectory() ? it : 
    zipTree(it) } 
    }
   with jar
}

并将implementation 'com.google.guava:guava:24.0-jre'更改为compile 'com.google.guava:guava:24.0-jre',然后在生成的jar中包含番石榴

并运行命令gradle fatJar

source = https://www.mkyong.com/gradle/gradle-create-a-jar-file-with-dependencies/