Gradle: Part 4, Creating a fat jar using Gradle

Gradle: Part 4, Creating a fat jar using Gradle

In this part, we will create an executable fat jar with dependencies using Gradle task or you can say we will create an executable jar which contains all dependencies. This part is a continuation of Java Project set up using gradle.

What is Gradle Task

In a simple sense, a task is a groovy/koltin function. Let’s start by writing a simple task. Go to build.gradle and write a task as such

task hello {
        println 'Hello world!'
}

and execute it as gradle hello and you can see the output as


> Configure project :
Hello world!

Now, this is a very simple task that only prints but you can create a task to perform any action like copying the file before compiling, etc. We will use the task to create an executable fat jar. Before we create this task, we must know that Gradle supports two types of tasks: a simple task and custom task.

A simple task is basically a default task or a task that is provided by the id in the plugin i.e in our case application plugin provides us the run task. Now we can override this task to add more functionalities, e.g. if you want to pass System properties to your project you can override it as

run {
    systemProperties System.getProperties()
}

Now you can run it using cmd as

gradle -Dconf.path=/xyz/conf.yml run

or passing VM options in IntelliJ run configuration and for testing, you can read it as

System.getProperty("conf.path") in code.

But sometimes default tasks are not enough. We might want to create a custom task; we can do that in gradle e.g

task hello {
        println 'Hello world!'
}

is a custom task. Note that in case of default task we define the task with an action closure, we don’t need to add a task in front of the task, but in case of a custom task, we need to do that.

Creating executable fat jar using Gradle custom task

We will create a custom task to create an executable fat jar with dependencies. In build.gradle add as under

version = '1.1.0'

task fatJar(type: Jar) {
    manifest {
        attributes 'Main-Class': "${mainClassName}"
    }
    baseName = "${rootProject.name}"
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

The mainClassName is already defined in our build.gradle and rootProject.name is already by default defined in settings.gradle. So now run gradle clean fatJar. And now you can see a jar under build/libs in the test-gradle folder.

You can now run it as

java -jar build/libs/{jar_name}.

In my case jar name is test-gradle-1.1.0.jar. So now I can also execute it as

java -Dconf.path=/xyz/conf.yml -jar build/libs/test-gradle-1.1.0.jar

Note: I am passing system variables here

So that’s it! Deploy this jar where it’s needed.

Happy Coding!!!

Share This Post

Post Comment