How do I create an executable fat jar with Gradle with implementation dependencies

You can use the following code.

jar {
    manifest {
        attributes(
                'Main-Class': 'com.package.YourClass'
        )
    }
    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
 }

Be sure to replace com.package.YourClass with the fully qualified class name containing static void main( String args[] ).

This will pack the runtime dependencies. Check the docs if you need more info.


Based on the accepted answer, I needed to add one more line of code:

task fatJar(type: Jar) {
  manifest {
    attributes 'Main-Class': 'com.yourpackage.Main'
  }
  archiveClassifier = "all"
  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
  with jar
}

Without this additional line, it omitted my source files and only added the dependencies:

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

The same task can be achieved using Gradle Kotlin DSL in a similar way:

val jar by tasks.getting(Jar::class) {
    manifest {
        attributes["Main-Class"] = "com.package.YourClass"
    }

    from(configurations
        .runtime
        // .get() uncomment this on Gradle 6+
        // .files
        .map { if (it.isDirectory) it else zipTree(it) })
}