Gradle is an open-source build tool that was initially released in 2007 and stably released in 2019. It uses Directed Acyclic Graphs (DAG) to define the order of the process that needs to be executed and introduces a Java and Groovy-based Domain Specific Language (DML). This Gradle tutorial is designed for both beginners and professionals. Here, we would be covering basic and advanced concepts of the Gradle tool such as -

Gradle Tutorial | A Beginners Guide to Learn Gradle Java Build Tool - [Updated]

  • What are the build tools
  • What is Gradle
  • Features of Gradle
  • How to install Gradle on Windows 
  • How to install Gradle on Mac OS
  • Advantages of Gradle
  • Gradle Eclipse Integration
  • Gradle dependencies and management
  • Gradle repository
  • Gradle Build Scans
  • Gradle multi-project builds
  • Gradle Wrapper
  • Gradle Vs Maven comparison
  • Gradle Vs Jenkins
  • Gradle Vs Ant
  • Conclusion

What are Build Tools?

In software development and testing, build tools are used. Build tools are the programs that are used to automate the process of compiling, testing, and deploying of source code efficiently. These tools help developers focus on actual software development activities rather than doing drudge work. 

Some of the most commonly used build tools are -

  • Gradle
  • Apache Ant
  • Apache Maven
  • Grunt
  • Gulp and more

In this tutorial, we would be learning about Gradle step by step and also compare it with other build tools available in the market. Moreover, we will find advantages of Gradle and why we should use it.  

What is Gradle?

Gradle can build automation on many platforms and languages such as Java, Android, C, C++, Groovy, and Scala and provides integration with many development tools and servers including Eclipse, Jenkins, IntelliJ and Android Studio.

Features of Gradle

  • High Performance - Gradle avoids unnecessary tasks and providers faster performance by reusing the output of the previous executions. It executes the tasks parallely and processes only those which have different inputs 
  • Extensibility - Gradle can be easily extended to provide task types and build models. 
  • Free and open-source - Gradle is an open-source tool which is licensed under the Apache Software License (ACL)
  • Gradle Wrapper - Gradle wrapper allows execution of Gradle builds even on those machines where Gradle is not installed. It is very helpful when there is a continuous integration of servers. 
  • Supports Ant Tasks -  Gradle provides support to the Ant build projects by importing Ant build project and reusing all its tasks. 
  • Build Scans - Build scans help us to diagnose the build issues which can be shared with others also. Sharing with others helps us to take advice and fix the issue accordingly.
  • IDE Support -Gradle supports several IDE's which can import and interact with Gradle Builds. 
  • Familiarity with Java - Gradle needs JVM to run and is also familiar with several Java features. It is a plus point for the Java users because they can use many Standard Java APIs to build logics.
  • Incremental Builds - Gradle executes only necessary tasks. Before compiling any source code, it will check whether the source code has changed since its last execution. If the code has changed, Gradle will execute it else it will skip the execution step and mark the task as updated.
  • Multi-project Build Support - Gradle supports multi-project builds. A multi-project build contains a root project and some subprojects which may also have subprojects

How to Install Gradle on Windows ?

Gradle is an open-source Java based build tool that combines the best features of Maven and Ant. Before getting to the installation process, let us first know the prerequisites for the Gradle.

Prerequisites 

Gradle is a Java-based tool, so it is mandatory to install Java 8 or higher version on your computer. Before installing the Gradle, ensure that the Java SDK 8 or higher version is already installed. 

To verify whether Java is installed on your system or not, you can use the command prompt.

After verifying, follow the below-given steps to install Gradle.

Step 1 - Visit the official website of Gradle and click on the option "Install Gradle". After that you will find many options to install Gradle.

Step 2 - Go to Installing manually option and click on "binary-only" to download the binary file.

Step 3 - The selected option will start downloading a Zip file. Go to download and right-click on the downloaded file and unzip it. Also, browse the location where you want to locate it.

Step 4 - Now we need to set the environment variables. For that, Right-click on "This PC or My computer" > Properties > Advanced system settings > Environment variables. You will see the box as shown below.

Step 5 - You can now click on “New” to create a new variable. Give a name to the variable and in the variable value section, you have to give the location where the Gradle folder is stored.

Now, this variable name given by you will appear in the user variable list as shown below.

After that, click on “Path” and then “New”. Add the location of the Gradle bin folder and press OK.

Step 6 - Now, you have to verify whether Gradle is installed in your system or not using command prompt.

This screen shows that the Gradle tool is installed in your system.

How to Install Gradle on Mac OS ?

There are two ways of installing Gradle on Mac OS - Manually and using homebrew. But before that, you need to ensure you have installed the Java 8 or above version on your system. The process of installing Gradle on Mac OS manually is very similar to that of installing Gradle on Windows manually. The only thing that differs is the way of setting the environment variables. 

Steps to Download Gradle on Mac OS

Step 1 - Use command prompt to check whether Java 8 or above version is installed as shown in Windows. If yes, skip this step.

Step 2 - Download the Gradle from the Official page and create a directory to unzip the downloaded file.

  • Create a directory

Unzip the downloaded file

Step 3 - Next is to set up the environment variable by running the following command.

Step 4 - In the next step, we will source the bash config file.

Step 5 - In the last step, we have to verify the Gradle installation by running the below command.

Advantages of Gradle 

  • Highly Customizable - Gradle is highly customizable and extensible. It can be used in Java projects, Groovy projects, android projects and more. 
  • Performance - Gradle offers faster performance using build cache. It executes only those tasks that have different input, the task with the same inputs gets stored in cache and is used when needed.
  • General-purpose build tool - Gradle is a general purpose build tool which can be used to build several types of software.
  • User Experience - Gradle supports various IDEs and offers friendly user experience. Users who like to work on the terminal, Gradle provides a command line interface for them. 

Gradle Eclipse Integration

Subscribe to our youtube channel to get new updates..!

Open eclipse > Help > Eclipse Marketplace

A box will pop up of Eclipse Marketplace. There, a 'Find' search box will be present, from there you have to search  Gradle and then select buildship gradle integration.

Click on the install button and then gradle will get installed in Eclipse. After that Eclipse will automatically restart.

---Also Read - An Ultimate List of Open Source Java Build Tools

Gradle Dependencies and Management

Projects may have dependencies ie; they may require JAR files from other projects or external JARs in the classpath. We can say that most of the projects are not self-contained. Dependency configuration is a collection of dependencies and artifacts. There three main tasks in the configuration -

  • Declaring dependencies
  • Resolving the dependencies and, 
  • Exposing artifacts for consumptions

Dependency is an essential part of projects and can be used on different phases of the project such as - Compile, Runtime, Test Compile and Test Runtime. We must declare dependencies which we want to download from the web.

  • Compile - Dependencies that are needed for compiling the production source of the project.
  • Runtime - Dependencies that are used at runtime for production classes. Also, by default, they contain the compile-time dependencies. 
  • Test Compile - These dependencies are needed to compile the test source of the project. It also contains compile-time dependencies and compiled production classes.
  • Test Runtime - These dependencies are needed to run the tests. It contains test and runtime compile dependencies.

External Dependencies

This is a dependency on the files that are built outside the current build and are stored in the repository. Below, a code snippet is given that is used to define the external dependency. 

Gradle Repositories

Dependencies come in the form of modules and the location where these modules are stored are called as repositories. Gradle specifies these repositories to retrieve the module for the project. Repositories are of different forms - local directory and remote repository.

A repository is a collection of files that are organized by group, name and the version. By default, Gradle does not define repositories but we need to define at least one. At runtime, Gradle finds out the declared dependencies that are required to process the tasks. Once the dependency is resolved, important files of dependency are stored in the local cache memory also referred as remote repository. Future build can reuse these saved files to avoid unnecessary network calls. Gradle supports different repository formats -

  • Ivy repositories
  • Maven repository
  • Flat directory repository

How to Add Repository to Gradle Project?

Different repository formats can be added to projects by adding that specific code snippet to the 'build.gradle' file.

To add repository to the project, we need to declare its URL address or its location in the 'build.gradle' file

  • Adding a Maven repository using its URL
  • Adding a Maven repository using its Location in the file system

Dependency Management

Dependency management is a process of declaring, resolving and using the dependencies required by the project. Gradle has built-in support for dependency management and for that following things are needed -

  • Gradle should be aware of the requirement to run a project. 
  • Gradle needs to build and also upload the data produced by the project.

Most of the projects need files that are built by other projects for their compilation. These files are said to be the dependency of the project. Gradle specifies the dependencies, finds them and makes them available in a project. These dependencies can be downloaded from remote Ivy or Maven repository or we can also build our dependencies and include them in the project. This process is called dependency resolution.

Suppose file A is dependent on file B and also file is dependent on file C. This process is called transitive dependency.

Gradle Build Scans

A build scan is a centralized record that provides insights into the details of the Gradle project. It is shareable and can be accessed from the Gradle remote server. 

How to Create Build Scans?

To create a build scan, the first step would be to create a Gradle project. Let us see how to create build scans step by step. 

Step 1- Create a Gradle project

We can clone a project from GitHub or use the existing project. But to create a new project, use the below command.

Step 2 - Apply the Build Scan plugin

From Gradle 4.3 onwards, there is no need to add any additional configuration to enable build scans. The required build scan plugin gets applied automatically when we use the -scan option.

To publish a build scan, you need to accept the Gradle terms by selecting option 'Yes'. Execute the below-given command to publish a build scan. 

After running the command, you are going to get this output screen. The green link is used to access the build scan. 

-Also Read - Frequently Asked Gradle Interview Questions

How to Access the Build Scan Online

To access the build scan online, go to the generated link and activate the build scan. Enter your email id and choose the 'Go' option. 

After that, you will receive a link in the given email id to activate the build scan. Check you inbox and follow the link.

Click on ‘Discover your build’ and explore the created build.

The above image shows the information about the create build scan such as  console log, timeline, failure points, performance, tests, dependencies, plugins, projects, switches, execution time, infrastructure and more.

Multi-Project Build in Gradle

A multi-project consists of a root project and multiple subprojects. Gradle promotes multi-project build to accelerate project development and takes care of the dependencies that occurred from other parts of the project. 

Cross-Project Configuration and Execution

Each of the subprojects in Gradle is capable of configuring itself in complete isolation, therefore, the subprojects share common characteristics. Here, configuration means execution of 'build.gradle' of a project. By default, configurations are done before the execution of any task. After configuration, a project becomes more flexible in case of updating or accessing any module of a project.

Create a Multi-Project

Let us create a project where the root project name is Multi_project and its subproject name is sub_project. Now, create a new directory using the command : mkdir Multi_project. Then create a Gradle build by running the init command. The init command includes a wrapper command which creates the build.gradle and setting.gradle file in the root project. 

After executing the init command, user needs to enter the type of project from the four given options -

  1. Basic
  2. Application
  3. Library
  4. Gradle plugin

Then, it will ask to select the build script DSL from two available options -

  1. Groovy
  2. Kotlin

After that, enter the project name and press enter to continue. 

Multi_project/

build.gradle

setting.gradle

Sub_project/

build.gradle

setting.gradle

Add the below-given code snippet in the root project build script to create the multi-project build.

To include the subproject into the root project, add the below statements in the setting.gradle.

To execute, use the command : gradle -q hello. You will get an output screen as shown below -

To execute, use the command : gradle -q hello. You will get an output screen as shown below -

Access the Subproject

Gradle project API allows users to access the subprojects only. For that, define a common behaviour of the project and subproject. Let us see how to write the code for it. 

Now, execute the command : gradle -q hello  and get output screen given below

Gradle Wrapper

Installing a software and ensuring that it is the right version can be pretty difficult for the user. But with Gradle wrapper, a user can overcome all these challenges.

Wrapper is a batch of script that invokes a declared version of Gradle automatically. The Gradle wrapper helps developers to run a build without following the manual installation process. It saves the company's time and money. 

Gradlew.bat file for Windows systems and gradlew file for Unix based systems acts as a gradle commands used in case Gradle is not installed on the machine. 

Benefits of Gradle Wrapper

There are following benefits of using Gradle Wrapper -

  • There is no need to install Gradle on your machine
  • The wrapper guarantees you will be using the right version of Gradle required by the project
  • A user can easily update the project to the newer version of Gradle

In the coming sections, we would be discussing three different workflows -

  • How to add the Wrapper?
  • How to run a project with the already provided wrapper?
  • How to upgrade the wrapper to a new version of Gradle?

How to Add the Wrapper?

Gradle has a built-in task called Wrapper. On execution of wrapper task, necessary wrapper files are generated in the project directory. To run the wrapper task, use the below command 

gradle wrapper

The generated wrapper properties file contains following information about Gradle distribution -

  • Server hosting the Gradle distribution
  • Type of Gradle distribution
  • Gradle version

All the above aspect can be configured by executing the following command line -

  • To specify the gradle version use : --gradle-version
  • To specify the gradle distribution type : --distribution-type
  • To point the full URL of the Gradle distribution zip files : --gradle-distribution-url

How to Use the Gradle Wrapper?

It is always preferred to execute a build using wrapper for reliable and standardized execution of the build. Depending on the OS, a user can either use gradlew or gardlew.bat instead of using the gradle command. In case the Gradle distribution is not present on the system, Wrapper will download and store it in the local file system. 

How to upgrade the wrapper to a new version of Gradle?

It is important to update the software to get the benefits of new features and improvements. We can manually upgrade the Gradle to the newer version by changing the URL properties in the wrapper property file. But it would be better to upgrade the wrapper through the wrapper task. 

To upgrade a Gradle wrapper to a particular version, run the below command

To check the specified version of the Gradle, we can run the following command : gradle -version

Customizing the Gradle Wrapper

Although, default runtime behaviour of Gradle is good but sometimes we need to customize the wrapper as per organization requirement. The built-in wrapper task gives numerous options to customize the runtime behaviour as per your needs. 

Gradle Vs Maven comparison

Gradle is one of the best build tools available for Java. Maven was developed before gradle and is generally used alternatively. It is tough to decide which build tool is best suited for our project with different frameworks. Here, we would be comparing Gradle Vs Maven that is helpful in deciding which matches our project needs better.

 

Gradle Maven
It is a build automation tool that used domain specific language It is a software management system that is basically used for Java projects.
Gradle avoids the compilation of Java Compilation is mandatory in Maven
It does not uses XML file to declare the project configuration It uses an XML file to declare the project, dependencies, build order and required plugin
Highly customizable and offers wide range of IDE support custom builds It has limited number of parameters so customization is pretty difficult
It gives faster performance by running only those tasks that have different inputs Build time is slower than Gradle
Main goal is to add functionality to the project Main goal is related to the project phase
Based on the graph of task dependencies that do the work Based on the phases of linear and fixed model

Gradle Vs Jenkins

   Gradle   Jenkins
Open source build tool written in Kotlin, Java, and Groovy Open source build tool written in Java
It supports multi-project builds It does not support multi-project builds
Allows easy migration to other tools Jenkins does not provide the migration from other tools
It is not an integration server It is a continuous integration server
It facilitates with only two types of plugins to support build process It facilitates with around 300 plugins to support build process
It integrates with several development tools and server such as Eclipse, IntelliJ, Android studio and Jenkins It integrates all types of SDLC processes such as build, stage, package, deploy, static analysis, document and more

Gradle vs Ant

  Gradle    Ant
Gradle is a Groovy-based build automation tool Ant is a Java-based build automation tool.
Gradle supports multi-project build It does  not support multi project build
More standardized Less flexible
Gradle provides comfortable support to IDE  integration IDE integration is slightly complex
Gradle provides a structured build Ant does not impose project structured
Gradle is developed to overcome all the drawbacks of Ant and Maven Ant is developed to overcome the drawback of the make build tool of Unix
Uses DSL (Domain Specific Language) instead of XML It uses XML files to define build scripts

This was all about Gradle, hope you found the information useful. In case you come across any doubt, please drop the query in the comment box.