简体   繁体   中英

Java Gradle Build: NoClassDefFoundError

My build.gradle file is as following

apply plugin: 'java' sourceCompatibility = 1.8

repositories {
    mavenCentral() }


dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile 'io.javalin:javalin:1.3.0'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'
    compile 'org.slf4j:slf4j-simple:1.7.25' }

jar {
    manifest {
        attributes(
                'Class-Path': configurations.runtime.files.collect {"$it.name"}.join(' '),
                'Main-Class': 'products.ProductAPI'
        )
    } }

task stage {
    dependsOn 'build'
    dependsOn 'clean'
    build.mustRunAfter clean }

Trying to build a java application with gradle and deploy it to a heroku server. I have some issues on java -jar build/libs/MyApp-0.0.1.jar as it returns the following:

Exception in thread "main" java.lang.NoClassDefFoundError: io/javalin/Javalin at products.ProductAPI.main(ProductAPI.java:7) Caused by: java.lang.ClassNotFoundException: io.javalin.Javalin 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)

To run your app without any NoClassDefFoundError , you should have your dependencies in the runtime class path. Creating a fat jar is the simplest solution. Change your jar section like below;

jar {
    manifest {
       attributes(
          'Class-Path': configurations.compile.files.collect {"$it.name"}.join(' '),
          'Main-Class': 'products.ProductAPI')}
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

run gradle build command and jar with dependencies will be created. Other way is to add jars to runtime class path are; with java -cp flag. (Also If your application has already a classpath folder configured, copying dependencies in this folder will add them to the classpath)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM