Create an executable FatJar in Gradle

Fat Jar is also know as uber jar which consists of all the classes along with the dependencies required to the run the application.

Setup build.gradle

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    compile jackson_libraries.core
    compile jackson_libraries.databind
    compile jackson_libraries.annotations
}

Override the default JAR task

By default jar task build jar without any dependencies, we will override the behavior of the jar task by adding a few lines of code in the build.gradle which will include all the dependencies to the jar.

jar {
    manifest {
        attributes "Main-Class": "in.asvignesh.MainClass"
    }

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

The final gradle file will look like

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    compile jackson_libraries.core
    compile jackson_libraries.databind
    compile jackson_libraries.annotations
}

jar {
    manifest {
        attributes "Main-Class": "in.asvignesh.MainClass"
    }

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

Now running the jar will generate the executable jar with the dependencies.


Also published on Medium.

Vignesh A Sathiyanantham
AWS Certified developer with 8 years of extensive experience working for Cloud and Datacenter solutions and leading a small team in a lean startup based on Bangalore, India

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.