Build Your Code: A Complete, Introductory Gradle Tutorial

6 min read
Stay connected

The post you’re about to read is a tutorial about the open-source build automation tool called Gradle. Why is learning Gradle a good use of your time?

Well, when it comes to developing software, learning a programming language isn’t the only thing you need to do, despite being a crucial step. It’s also essential you learn the surrounding ecosystem of the programming language, with all its auxiliary tools, such as unit testing frameworks, logging libraries, and—you guessed it—build tools.

In this post, we’ll give you a complete introductory guide to Gradle. You’ll learn, in a totally hands-on way, how to use this tool to build a Java codebase.

Requirements

Before we start with the tutorial, let’s make sure you have everything you need. Here are the requirements:

  • The Java SDK installed on your system.

  • An IDE or text editor. I’ll use the free community version of IntelliJ IDEA, but use whatever you’re most comfortable with.

  • Some familiarity with working with the command line.

Got everything you need? Then let’s get started.

Gradle Tutorial: Build a Java Codebase in Less Than 15 Minutes

You’ll now see how to go from zero to hero in Gradle in just a few steps.

Step #1: Obtain the Sample Application

We won’t walk you through the creation of a Java application for two reasons. First, this isn’t a Java tutorial. Second, it would probably take too long. 

What we will do instead is provide you with an already-built application. Visit this GitHub repo and clone or download the code.

Step #2: Install Gradle

The second step is installing Gradle itself. We’ll briefly cover how to do that on three different platforms.

macOS

The easiest way to install Gradle on macOS is probably by using the Homebrew package manager. Just run the following command:

$ brew install gradle

Linux

If you’re on Ubuntu, you can easily install Gradle using the software store. Just search for Gradle and then install it as you normally would:

A more manual method would be downloading the binaries, adding them to a directory, and adding that to the system path. These steps are inspired by this article, updating it when necessary.

Let’s start by downloading the latest release (at the time of this writing, 7.2) and unzipping it:

wget https://services.gradle.org/distributions/gradle-7.2-bin.zip -P /tmp
sudo unzip -d /opt/gradle /tmp/gradle-7.2.zip

After that, use whatever text editor you like to create a new file called gradle.sh. Place it in the /etc/profile.d/ directory. The file should have this content:

export GRADLE_HOME=/opt/gradle/gradle-7.2
export PATH=${GRADLE_HOME}/bin:${PATH}

Then, make the file executable and load the environmental variables:

sudo chmod +x /etc/profile.d/gradle.sh
source /etc/profile.d/gradle.sh

To check whether everything worked out fine, run gradle --version. You should see an output like this:

------------------------Gradle7.2--------------------------------------
Build time:   2021-08-17 09:59:03 UTC
Revision:     a773786b58bb28710e3dc96c4d1a7063628952ad
Kotlin:       1.5.21
Groovy:       3.0.8
Ant:          Apache Ant(TM) version 1.10.9 compiled on September 27 2020
JVM:          1.8.0_292 (Private Build 25.292-b10)
OS:           Linux 5.11.0-38-generic amd64

Windows

You can install Gradle on Windows by simply downloading it, extracting to a folder, and then adding that folder to the system path.

As you’ve seen, at the time of this writing, the latest release of Gradle is 7.2. Go to the download page and grab it. Extract the contents of the .zip to a folder of your preference, and add that location to the system path.

Alternatively, you can use Chocolatey. Just run the following command:

choco install gradle

At the time of this writing, as far as I know, it’s not possible to install Gradle using the Windows Package Manager (winget).

Regardless of the method you pick, you can test the installation by running:

gradle --version

Step #3: Build Your First Java Codebase With Gradle

By now, you already have everything in place to start building with Gradle. So, let’s do just that.

The first step is to create a Gradle file, which will store the necessary configurations for the tasks we want Gradle to carry out.

Using your favorite editor, create a new text file at the root of the project’s folder. Name it build.gradle. Then paste the following lines on it:

plugins {
    id 'java'
}

Those lines add the Java plugin to your configuration. Its plugin architecture allows Gradle to remain very small and simple but flexible at the same time, since valuable functionality can be added via plugins.

Additionally, add the following lines to your file:

jar {
    manifest {
        attributes(
                'Main-Class': 'main.java.demo.Main'
        )
    }
}

Those lines define the entry point of the application so you can execute it as the resulting .jar file.

Save the file. We’re now ready for the final step, which is to execute the build task. Just go to your terminal and run the following command:

gradle build

If everything went right, you should see a result like this:

Now, let’s test our built application. You should see a build directory inside your project’s folder. Access it and you’ll see a few directories hanging there:

cd build
ls


Mode                 LastWriteTime         Length Name                                                                 
----                 -------------         ------ ----                                                                 
d-----        06/11/2021     12:59                classes                                                              
d-----        06/11/2021     12:59                generated                                                            
d-----        06/11/2021     12:59                libs                                                                 
d-----        06/11/2021     12:59                tmp    

Access the libs directory and you should see a file named gradle-demo.jar. Run it with the following command:

java -jar gradle-demo.jar

The program should run as normal:

Gradle Tutorial One Step Further: Adding Dependencies

Most real-world applications rely on software made by third parties, which we call dependencies. In the past, managing dependencies used to be a real headache for developers. Nowadays, most modern programming environments use some dependency management strategy that relies on listing the dependencies with their versions in text format and using a command-line interface (CLI) utility to download and update those dependencies as needed.

You can—and should—declare your dependencies using Gradle. Let’s see how to do that, declaring log4j2—a widely popular logging library—as a dependency.

Start by adding the following lines to your build.gradle file:

dependencies {
  compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.14.1'
  compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.14.1'
}

Going back to your Main.java class, add the following two imports:

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

Then, go to the bottom of the Main method and add the following two lines:

Logger logger = LogManager.getLogger(Main.class);
logger.info("Displaying information about user name.");

Now, just run gradle build again. The build task should succeed, proving that Gradle successfully resolved those dependencies.

Java + Gradle for Fun and Profit

Gradle runs on the Java Virtual Machine (JVM). It’s a very flexible tool, allowing you to build projects in several different languages. Also, its architecture allows its core part to remain quite small and simple while leveraging the power of many plugins.

In this post, you’ve learned how to install Gradle and build a simple Java project. You’ve also learned how easy it is to use Gradle to declare and resolve dependencies.

What should your next steps be? Well, there’s a universe to be learned when it comes to Gradle. Here are a few suggestions:

  • Learn about the different plugins available at your disposal.

  • Get familiar with the main Gradle tasks.

  • Learn how to create your own tasks.

  • Take a look at some alternatives to Gradle, such as Maven.

Regardless of how you do it, use the knowledge you gained today and build upon it. Thanks for reading!

This post was written by Carlos Schults. Carlos is a consultant and software engineer with experience in desktop, web, and mobile development. Though his primary language is C#, he has experience with a number of languages and platforms. His main interests include automated testing, version control, and code quality.

Stay up to date

We'll never share your email address and you can opt out at any time, we promise.

Loading form...
Your ad blocker may be blocking functionality on this page. Please disable for an improved experience.