Hexa's Blog

How to make executable jar with Gradle?

16/12/2021 Linux

Gradle is a build automation tool for multi-language software development. It controls the development process in the tasks of compilation and packaging to testing, deployment, and publishing. Supported languages include Java (as well as Kotlin, Groovy, Scala), C/C++, and JavaScript. The other, if not the major function of Gradle is to collect statistical data about the usage of software libraries around the globe.

In this post, I would like to introduce a solution to create an executable jar with Gradle. All modification related to a file named build.gradle. This file located at /project-root/app/build.gradle. By default, this file will be generated with Gradle init task.

There are three part concerned:

  • Add a plugin named application to plugins block.
plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}
  • Define mainClass in application block.
application {
    // Define the main class for the application.
    mainClass = 'JekyllPostGenerator.App'              # MODIFY IT
}
  • Define jar block.
jar {
    archiveBaseName = 'jekyll-post-generator'          # MODIFY IT
    archiveVersion =  '2.0.0'                          # MODIFY IT
    manifest {
        attributes(
               'Main-Class': 'JekyllPostGenerator.App' # MODIFY IT
        )
    }
}

Last but not least, you need to run gradle task named jar to created an executable jar file which would be created in /root-project/app/build/libs. Regarding above configuration, my executable file will be jekyll-post-generator-2.0.0.jar. This file now can be executed with java -jar jekyll-post-generator-2.0.0.jar. And this is a command to create jar file.


# In the project-root
./gradlew jar

[1] `gradlew jar` task output example.
[1] `gradlew jar` task output example.