Gradle Command to Build Jar

In this guide, we'll explore the steps and commands necessary to create a JAR file using Gradle.

Pre-requisites

  1. A Java project set up with Gradle. If you don't have one, you can start by creating a simple project using the gradle init command or from an existing source. 
  2. Gradle installed locally (or use the Gradle Wrapper, which comes bundled in most modern Java projects).

Building the JAR 

1. Navigate to your project directory 

Open your terminal or command prompt and navigate to the root directory of your Gradle project. 

2. Execute the JAR task 

Run the following command:
gradle jar
If your project includes the Gradle Wrapper (which is recommended for ensuring consistent builds):
./gradlew jar
On Windows:

gradlew.bat jar

3. Locate the JAR 

After executing the command, Gradle will compile your project and package it into a JAR file. 

By default, you can find this JAR in the build/libs directory of your project. 

What's happening behind the scenes? 

When you issue the jar task: 
Compilation: Gradle compiles the project's source code. 

Packaging: All compiled classes and resources are packaged into a JAR file. 

Output: The JAR file is saved in the build/libs directory with a default name pattern: 
jar {
    manifest {
        attributes 'Implementation-Title': 'My Project',
                   'Implementation-Version': '1.0'
    }

    // Exclude test classes, for example
    exclude '**/*Test.class'
}

Customizing the JAR Packaging 

You can customize the packaging process using the jar task in your build.gradle file. For instance, if you want to change the manifest or include/exclude certain files:
jar {
    manifest {
        attributes 'Implementation-Title': 'My Project',
                   'Implementation-Version': '1.0'
    }

    // Exclude test classes, for example
    exclude '**/*Test.class'
}

Building an Executable JAR 

In case you're working with Spring Boot or other frameworks that require an executable JAR, you'd usually rely on specific plugins (like spring-boot-gradle-plugin). Once the plugin is applied, you can use:

gradle bootJar
This will produce an executable JAR with embedded dependencies, ensuring your application can run standalone.

Comments