How to Build Java Application Using Gradle?

build java application using gradle

In this blog, you will learn to build Java Application using Gradle.

In this step-by-step blog, we will cover everything you need to know about building a Java Application using Gradle.

What is Gradle?

Gradle is an open-source build tool that automates the process of compiling, testing, and packaging the code, and its configuration files are written in Groovy.

It supports almost every language but is mostly used for projects using languages like Java, Kotlin, C/C++, etc.

Gradle is highly customizable and supports a wide range of IDEs. IDE stands for an integrated development environment which is software that combines the capability of compiling, testing and packaging applications.

Why should we use Gradle?

Gradle is faster, highly scalable, and can be used to build large projects. For example, Netflix and Android are primarily built on Java, and they use Gradle as their building tool.

Gradle was created to combine the advantages of Maven and Ant and also to reduce the issues while using them.

For example, Maven and Ant build files are XML-based, which is a bit difficult to understand, but Gradle build files are based on Groovy or Kotlin, which is easily understandable.

Maven rebuilds the whole project again for code changes, but Gradle only rebuilds the part where the code is changed. This is one of the main advantages of Gradle, which decreases build time.

Gradle supports multi-project builds, which means it can split large projects into subprojects with its own build files. An example multi-project structure is given below:

ecommerce/
├── settings.gradle
├── build.gradle
├── web/
│   └── build.gradle
├── service/
│   └── build.gradle
└── data/
    └── build.gradle

Prerequisites

To build a Java application with Gradle, you need the following installed on your system.

  1. Java JDK
  2. Gradle

How to use Gradle to Build Java Application?

To build a simple Java application, clone the following repository to your workspace.

git clone https://github.com/techiescamp/java-app.git

The structure of the repository is given below.

.
├── README.md
├── .github
├── build.gradle
├── pom.xml
├── settings.gradle
└── src
    ├── main
    │   └── java
    │       └── springboot
    │           └── Application.java
    └── test
        └── java
            └── springboot
                └── ApplicationTest.java

The build.gradle file contains all the requirements for the application, like plugins, dependencies, and the repository where the dependencies are downloaded from.

plugins {
    id 'org.springframework.boot' version '3.4.1'
    id 'io.spring.dependency-management' version '1.1.7'
    id 'java'
}

group = 'springboot'
version = '1.0.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

test {
    useJUnitPlatform()
}
  1. The plugin block configures the springframework, dependency-management, and Java plugins to the application for springboot and dependency management.
  2. In the group and version, we specify the project ID and version.
  3. The repositories block specifies the repository from which the dependencies will be downloaded, in this case it mavenCentral repository.
  4. In the dependencies block, we specify the dependencies needed, this downloads the springboot starter web dependency for web applications and the springboot starter test for testing.
  5. In the Java toolchain block, we specify the required Java version.
  6. In the final test block, we specify the JUnitPlatform for running the test case.

The settings.gradle file is where the root project name is specified.

rootProject.name = 'spring-boot'

The src folder contains two subfolders, main and test. The main/java/springboot folder contains the application’s source code.

package springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @GetMapping("/")
    public String index() {
        return "Hi from Spring Boot";
    }
}

It is a simple spring boot application that says “Hi from Spring Boot” while we run.

The test/java/springboot folder contains the test case for source code.

package springboot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void indexEndpointReturnsExpectedMessage() throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hi from Spring Boot"));
    }
}

This test checks if the endpoint returns HTTP 200 status with the expected message “Hi from Spring Boot.”

The pom.xml file is used when you build the Java application using Maven, not when building with Gradle.

pom.xml is a similar file like build.gradle, it contains all the requirements for the application, like plugins, dependencies, etc…

pom.xml is for building Java applications using Maven and build.gradle is for building Java applications using Gradle.

Let’s start building the Java application using Gradle, go to the root directory using the following command.

cd java-app

Before building the application, you can check if the application is working properly by running the following command from the root directory, which is java-app.

gradle bootRun

This runs your application, and you can access it on the web using the URL http://localhost:8080.

Now, run the following command from the root directory to build the application using Gradle.

gradle build

Once the build is completed, you can find the JAR file inside the build/libs/ directory as shown below.

jar file directory

To run the JAR file, run the following command.

java -jar build/libs/spring-boot-1.0.0-SNAPSHOT.jar

You can add the symbol & at the end of the above command to run the application in the background.

Once, it starts running you can access the application on the web using the URL http://localhost:8080, as shown below

accessing the application on web

You can use this JAR file to create a dockerized image of the Java application and deploy the Java application on Kubernetes.

Gradle Commands

Let’s look at other important Gradle commands that are not used in the example.

Init Command

The init command will create a basic project structure with every configuration file based on the project type you select.

Run the following command to create the project structure.

gradle init

This will ask a couple of questions to create the structure as shown below.

questions asked for creating project structure by gradle init command

Once you answer all the questions, your new project structure will be created based on your answers.

.
├── app
│   ├── build.gradle
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── org
│       │   │       └── example
│       │   │           └── App.java
│       │   └── resources
│       └── test
│           ├── java
│           │   └── org
│           │       └── example
│           │           └── AppTest.java
│           └── resources
├── gradle
│   ├── libs.versions.toml
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
└── settings.gradle

Gradle Scan Command

The Gradle scan command records the details of your build, such as execution time, plugins and dependencies used, etc… and shows it on the web.

To use Gradle scan, you have to use the --scan flag with the build command as given below.

gradle build --scan

Once the build is completed, it will ask a question whether your want to see the details of your build in the web, if you say yes, it will generate a link to access the page.

Then you have to give your Email ID on the page that appears when you press the above link, it will send the web page link to the specified ID.

Then, you can use the link from the Email to view the below page.

web report from gradle scan command

Gradle Profile Command

The profile command created a detailed report of the build in an HTML file, but not as detailed as the scan command.

This command is helpful in generating build reports on CI/CD workflows.

To use the Gradle profile, you have to use the --profile flag with the build command as given below.

gradle build --profile

You can find the HTML file inside the build/reports/profile directory, as shown below.

directory structure of html report file

If you run the HTML file, you can see the build details in the browser as shown below.

report generated by gradle profile command

What are the differences between Gradle and Maven?

The key differences between Gradle and Maven are listed below:

GradleMaven
Uses Groovy or Kotlin DSL based configuration fileUses XML based configuration file
It does not natively support cachingIt does not natively supports caching
Gradle build files are highly customizable and readableMavens build files are less customizable and complex
Building project fater than Maven and only rebuilds new changesBuild speed is slow, and rebuild the whole project if any changes are made
Supports multi-project builds nativelyAlso supports multi-project builds but needs additional configurations, which are complex
The directory structure can be customizedFixed directory sturcture. For example, src/main/java.
Supports languages like Java, C/C++, Groovy, etc…Supports languages like Java, Scala, C#, Ruby, etc…

Conclusion

In this guide, we have learned about the build tool Gradle, its configurations file, built a Java application using it, and additional important Gradle commands.

Not only that, we have also checked the application build by running the JAR file and accessing it on the web.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like