43

how to export a executable jar in gradle, and this jar can run as it include reference libraries.

build.gradle

apply plugin: 'java'

manifest.mainAttributes("Main-Class" : "com.botwave.analysis.LogAnalyzer")

repositories {
    mavenCentral()
}

dependencies {
    compile (
        'commons-codec:commons-codec:1.6',
        'commons-logging:commons-logging:1.1.1',
        'org.apache.httpcomponents:httpclient:4.2.1',
        'org.apache.httpcomponents:httpclient:4.2.1',
        'org.apache.httpcomponents:httpcore:4.2.1',
        'org.apache.httpcomponents:httpmime:4.2.1',
        'ch.qos.logback:logback-classic:1.0.6',
        'ch.qos.logback:logback-core:1.0.6',
        'org.slf4j:slf4j-api:1.6.0',
        'junit:junit:4.+'
    )
}

after i run : gradle build

it create the build folder, and i run the jar in build/libs/XXX.jar:

java -jar build/libs/XXX.jar

here is a execution says :

Exception in thread "main" java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException

how can i run it with the reference libraries?

5 Answers 5

18

You can achieve it with Gradle application plugin

7
  • Cool, I didn't know they had added this. I always used the "fat jar" recipe and manually added a manifest entry for the main class. Commented Feb 1, 2013 at 18:12
  • They added that somewhere around 1.0 release
    – erdi
    Commented Feb 1, 2013 at 19:05
  • 8
    and i don't want to get a zip or tar file, just need the dependencies libraries JARs in a folder
    – jychan
    Commented Feb 3, 2013 at 9:20
  • 11
    Gradle application plugin does not create an executable jar. Commented Nov 24, 2014 at 16:28
  • 1
    You can not achieve it with Gradle application plugin. Commented Feb 20, 2016 at 9:49
17

Hopefully this helps someone (as I unfortunately spent quite some time trying to find the solution). Here's the solution that worked for me for creating an executable JAR. I'm embedding Jetty in the main method, Jetty 9 to be specific and using Gradle 2.1.

Include the following code into your build.gradle file (if a subproject is the "main" project that the jar needs to be built from, then add it to the subproject which should start like this project(':') { insert the code somewhere here, after dependencies.}.

Also, you need to add the plugin java for this to work: apply plugin: 'java' .

My jar task looks as follows:

apply plugin: 'java'

jar {

    archiveName = "yourjar.jar"

    from {

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

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

    manifest {
        attributes 'Main-Class': 'your.package.name.Mainclassname'
    }

    exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA'
}

And then you can execute your yourjar.jar via the commandline:

java -jar yourjar.jar

The META-INF/.RSA, META-INF/.SF and META-INF/*.DSA have to be excluded for it to work. Otherwise a SecurityException gets thrown.

The problem seems to lie with embedded Jetty, as Jetty moved to Eclipse and now is signing their JARs, which I read becomes problematic when other, unsigned JARs want to load the signed ones. Please feel free to educate me if I am wrong in this, that's just what I read.

The JARs that the project depends on are defined in the dependencies as follows:

dependencies {

    // add the subprojects / modules that this depends on
    compile project(':subproject-1')
    compile project(':subproject-2')

    compile group: 'org.eclipse.jetty', name: 'jetty-server', version: '9.2.6.v20141205'
    compile group: 'org.eclipse.jetty', name: 'jetty-servlet', version: '9.2.6.v20141205'
    compile group: 'org.eclipse.jetty', name: 'jetty-http', version: '9.2.6.v20141205'

}

EDIT: Before, instead of just

configurations.runtime.collect{...}

i had

configurations.runtime.asFileTree.files.collect{...}

This caused strange behaviour in a larger project in clean build. When running the jar after executing gradle clean build for the first time (after manually cleaning the build directory), it would throw a NoClassDefFoundException (in our project with many subprojects), but running the jar after executing gradle clean build a second time (without emptying the build directory manually), for some reason it had all dependencies. This didn't happen if asFileTree.files was left out.

Also I should note, all compile dependencies are included in runtime, however not all runtime are included in compile. So if you are just using compile

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

Then be sure to remember that if there is a NoClassDefFoundException thrown, some class isn't found at runtime, which means you should also include this:

        configurations.runtime.collect {
            it.isDirectory() ? it : zipTree(it)
        }
4
  • I should also note that in my code the dependencies { ... } part comes before the jar { ... } part, in case it is relevant.
    – flamingo
    Commented Jan 23, 2015 at 15:49
  • -1 The OP is explicit: he/she wants to create a "fat jar" containing all the "reference libraries". You are not the only one to have answered the wrong question of course. See my answer. Commented Jan 18, 2017 at 20:10
  • I don't see where the OP uses the words "fat jar". The OP clearly speaks of an executable jar. I know that an executable jar basically is known as a fat jar, but does that immediately mean you have to use the fat jar plugin? Also i explicitly stated which versions I was working with, so yes this might be outdated, but it works with the gradle etc version that i mention.
    – flamingo
    Commented Feb 21, 2017 at 14:22
  • The OP didn't know the term "fat jar", I concur! But how else can this idea be interpreted: " this jar can run as it include reference libraries."? Surely this term "reference libraries" means the jars which constitute the dependencies... and the OP wants to know why she/he is getting the error message... a "fat jar" means an executable jar, yes, but specifically one containing all the dependency jars... Commented Feb 21, 2017 at 14:37
12

Quick answer

  1. Add the following to your build.gradle:

    apply plugin: 'application'
    
    mainClassName = 'org.example.app.MainClass'
    
    jar {
        manifest {
            attributes 'Main-Class': mainClassName,
                       'Class-Path': configurations.runtime.files.collect {"$it.name"}.join(' ')
        }
    }
    
  2. From the project directory, run gradle installDist
  3. Run java -jar build/install/<appname>/lib/<appname>.jar

I recommend adding the app version to your build.gradle as well, but it's not required. If you do, the built jar name will be <appname>-<version>.jar.

Note: I'm using gradle 2.5


Details

In order to create a self contained executable jar that you can simply run with:

java -jar appname.jar

you will need:

  1. your jar to include a MANIFEST file pointing to your application main class
  2. all your dependencies (classes from jars outside of your application) to be included or accessible somehow
  3. your MANIFEST file to include the correct classpath

As some other answers point out, you can use some third-party plugin to achieve this, such as shadow or one-jar.

I tried shadow, but didn't like the fact that all my dependencies and their resources were dumped flat out into the built jar together with my application code. I also prefer to minimize the use of external plugins.

Another option would be to use the gradle application plugin as @erdi answered above. Running gradle build will build a jar for you and nicely bundle it with all your dependencies in a zip/tar file. You can also just run gradle installDist to skip zipping.

However, as @jeremyjjbrown wrote in a comment there, the plugin does not create an executable jar per se. It creates a jar and a script which constructs the classpath and executes a command to run the main class of your app. You will not be able to run java -jar appname.jar.

To get the best of both worlds, follow the steps above which create your jar together with all your dependencies as separate jars and add the correct values to your MANIEST.

4
  • thanks, man that's work but about dependencies, if I want to create a jar with all dependencies?
    – max
    Commented Sep 29, 2016 at 7:03
  • @max sorry, I didn't fully understand your question. The above will create a single jar for your app which includes all your dependencies as separate jars. The MANIFEST classpath will point to all jars you are depending on.
    – elanh
    Commented Sep 29, 2016 at 9:21
  • 1
    YES that's correct but what if I want all my dependencies and app in single jar ?
    – max
    Commented Sep 29, 2016 at 11:40
  • @max I think you can use the shadow or one-jar plugins which I linked to in my answer.
    – elanh
    Commented Oct 5, 2016 at 9:14
7

All of these answers are either wrong or out of date.

The OP is asking for what is known as a "fat jar". That is an exectuable jar which contains all the dependencies so that it requires no outside dependencies in order to run (except for a JRE of course!).

The answer at the time of writing is the Gradle Shadow Jar plugin, explained pretty clearly at Shadow Plugin User Guide & Examples.

I struggled a bit. But this works:

put all these lines somewhere in your build.gradle file (I put them near the top) :

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.4' 
    }
}
apply plugin: 'com.github.johnrengelman.shadow'
shadowJar {
    baseName = 'shadow'
    classifier = null
    version = null
}
jar {
    manifest {
        attributes 'Class-Path': '/libs/a.jar'
        attributes 'Main-Class': 'core.MyClassContainingMainMethod'
    }
}

PS don't worry about any other "repositories", "dependency" or "plugin" lines elsewhere in your build file, and do leave the lines thus inside this "buildscript" block (I haven't a clue why you need to do that).

PPS the Shadow Plugin User Guide & Examples is well-written but doesn't tell you to include the line

attributes 'Main-Class': 'core.MyClassContainingMainMethod'

where I've put it above. Perhaps because the author assumes you are less clueless than I am, and you probably are. I haven't a clue why we are told to put a strange "Class-Path" attribute like that in, but if it ain't broke don't fix it.

When you then go

> gradle shadowjar

Gradle will hopefully build a fat executable jar under /build/libs (default name "shadow.jar") which you can run by doing this:

> java -jar shadow.jar
3
  • @elanh answer works just fine using gradle out of the box, no need for shadowjar
    – marcoslhc
    Commented May 10, 2017 at 17:26
  • @marcoslhc I don't think you've understood the question: the OP wants a jar which includes all its compile dependency jars. So you can take this jar and put it anywhere and go java -jar myFatJar.jar ... and it will run. elanh says the same thing in a comment to his question. Commented Jun 10, 2017 at 17:58
  • Save my day! This solution is working for my project as Feb 2018.
    – czxttkl
    Commented Feb 4, 2018 at 20:21
1

I checked quite some links for the solution, finally did the below mentioned steps to get it working. I am using Gradle 2.9.

Make the following changes in your build,gradle file :

1. Mention plugin:

apply plugin: 'eu.appsatori.fatjar'

2. Provide the Buildscript:

buildscript {
  repositories {
    jcenter()
   }

dependencies {
  classpath "eu.appsatori:gradle-fatjar-plugin:0.3"
  }
}

3. Provide the Main Class:

fatJar {
  classifier 'fat'
  manifest {
     attributes 'Main-Class': 'my.project.core.MyMainClass'
  }
  exclude 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.SF'
}

4. Create the fatjar:

./gradlew clean fatjar

5. Run the fatjar from /build/libs/ :

java -jar MyFatJar.jar
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.