Gradle - How pack dependencies into jar

11,148

Solution 1

To answer your question:

I want to build an independent jar which includes my code and all dependencies.

It sounds like you're asking how to build a "fat jar" in Gradle. You can do this with the JAR task like so:

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

That first line of code basically states to "jar up" all the configured dependencies under the "compile" dependency configuration. Obviously, if you had different dependencies in other dependency configurations that you wanted to include, you would include them as well or in place of, i.e.

configurations.runtime.collect { ... }

After running your build task or any tasks that creates the JAR, you should find all your project's dependency JARs in that respective archive.

Solution 2

Works on gradle 5, as is:

task buildJar(type: Jar) {
    manifest {
        attributes(
                'Main-Class': 'org.mycompany.mainclass'             
        )
    }
    classifier = 'all'
    baseName = 'MyJar'
    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
         }
            {
                exclude "META-INF/*.SF"
                exclude "META-INF/*.DSA"
                exclude "META-INF/*.RSA"
            }
    with jar
}

Jar will be placed at ./build/libs

Share:
11,148
Christoph Berghuber
Author by

Christoph Berghuber

Updated on June 05, 2022

Comments

  • Christoph Berghuber
    Christoph Berghuber almost 2 years

    I'm new to gradle.

    I have Java projects, with maven dependencies and local Java archive dependencies. I want to build an independent jar which includes my code and all dependencies.

    I've tried

    dependencies {
        runtime files(...)
        runtime group ...
    }
    

    to make libraries available when I run the program later, but it doesn't work, they are not available at runtime...

    I also tried this:

    from("$projectDir") {
        include '../lib/**';
    }
    

    but no success...the java program can't find the dependencies (NoClassDefFoundError) when I run it.

    • JB Nizet
      JB Nizet over 9 years
      Java doesn't load classes from jars in a jar, unless you use a special class loader that does that.
    • AKS
      AKS over 9 years
      its easy I think. under dependencies { compile fileTree(dir: "yourfolderwithpathwhereyouhavejarsetcfiles", include: "*.jar") }
  • Thufir
    Thufir almost 7 years
    what is the alternative idiom?
  • Andrea Gorrieri
    Andrea Gorrieri almost 3 years
    I have "no main manifest attribute" error trying to run the jar generated in this way