How to run gradle build
How to run gradle build
Gradle provides a command line to execute build script. It can execute more than one task at a time. This chapter explains how to execute multiple tasks using different options.
Executing Multiple Tasks
You can execute multiple tasks from a single build file. Gradle can handle the build file using gradle command. This command will compile each task in such an order that they are listed and execute each task along with the dependencies using different options.
Example
There are four tasks − task1, task2, task3, and task4. Task3 and task4 depends on task 1 and task2. Take a look at the following diagram.
In the above 4 tasks are dependent on each other represented with an arrow symbol. Take a look into the following code. Copy can paste it into build.gradle file.
You can use the following code for compiling and executing above task.
The output is stated below −
Excluding Tasks
While excluding a task from the execution, you can use –x option along with the Gradle command and mention the name of the task, which you want to exclude.
Use the following command to exclude task4 from the above script.
Cited below is the output of the code −
Continuing the Build
Gradle will abort execution and fail the build as soon as any task fails. You can continue the execution, even when a failure occurs. For this, you have to use –continue option with the gradle command. It handles each task separately along with their dependences.
The main point is that it will catch each encountered failure and report at the end of the execution of the build. Suppose, if a task fails, then the dependent subsequent tasks also will not be executed.
Selecting Which Build to Execute
When you run the gradle command, it looks for a build file in the current directory. You can use the –b option to select a particular build file along with absolute path.
The following example selects a project hello from myproject.gradle file, which is located in the subdir/.
You can use the following command to execute the above script.
This produces the following output −
Obtaining Build Information
Gradle provides several built-in tasks for retrieving the information details regarding the task and the project. This can be useful to understand the structure, the dependencies of your build and for debugging the problems.
You can use project report plugin to add tasks to your project, which will generate these reports.
Listing Projects
You can list the project hierarchy of the selected project and their sub projects using gradle –q projects command. Use the following command to list all the project in the build file. Here is the example,
The output is stated below −
The report shows the description of each project if specified. You can use the following command to specify the description. Paste it in the build.gradle file.
Listing Tasks
You can list all the tasks which belong to the multiple projects by using the following command.
The output is given herewith −
You can use the following command to display the information of all tasks.
When you execute the above code, you should see the following output −
The list of commands is given below along with the description.
Build Script Basics
This chapter introduces you to the basics of writing Gradle build scripts. It uses toy examples to explain basic functionality of Gradle, which is helpful to get an understanding of the basic concepts. Especially if you move to Gradle from other build tools like Ant and want to understand differences and advantages.
However, to get started with a standard project setup, you don’t even need to go into these concepts in detail. Instead, you can have a quick hands-on introduction, through our step-by-step samples.
Projects, plugins and tasks
Every Gradle build is made up of one or more projects. What a project represents depends on what it is that you are doing with Gradle. For example, a project might represent a library JAR or a web application. It might represent a distribution ZIP assembled from the JARs produced by other projects. A project does not necessarily represent a thing to be built. It might represent a thing to be done, such as deploying your application to staging or production environments. Don’t worry if this seems a little vague for now. Gradle’s build-by-convention support adds a more concrete definition for what a project is.
The work that Gradle can do on a project is defined by one or more tasks. A task represents some atomic piece of work which a build performs. This might be compiling some classes, creating a JAR, generating Javadoc, or publishing some archives to a repository.
Typically, tasks are provided by applying a plugin so that you do not have to define them yourself. Still, to give you an idea of what a task is, we will look at defining some simple tasks in a build with one project in this chapter.
Getting Started
Everyone has to start somewhere and if you’re new to Gradle, this is where to begin.
Before you start
In order to use Gradle effectively, you need to know what it is and understand some of its fundamental concepts. So before you start using Gradle in earnest, we highly recommend you read What is Gradle?.
Even if you’re experienced with using Gradle, we suggest you read the section 5 things you need to know about Gradle as it clears up some common misconceptions.
Installation
If all you want to do is run an existing Gradle build, then you don’t need to install Gradle if the build has a Gradle Wrapper, identifiable via the gradlew and/or gradlew.bat files in the root of the build. You just need to make sure your system satisfies Gradle’s prerequisites.
Android Studio comes with a working installation of Gradle, so you don’t need to install Gradle separately in that case.
In order to create a new build or add a Wrapper to an existing build, you will need to install Gradle according to these instructions. Note that there may be other ways to install Gradle in addition to those described on that page, since it’s nearly impossible to keep track of all the package managers out there.
Try Gradle
Actively using Gradle is a great way to learn about it, so once you’ve installed Gradle, try one of the introductory hands-on tutorials:
There are more samples available on the samples pages.
Command line vs IDEs
Some folks are hard-core command-line users, while others prefer to never leave the comfort of their IDE. Many people happily use both and Gradle endeavors not to discriminate. Gradle is supported by several major IDEs and everything that can be done from the command line is available to IDEs via the Tooling API.
Android Studio and IntelliJ IDEA users should consider using Kotlin DSL build scripts for the superior IDE support when editing them.
Executing Gradle builds
If you follow any of the tutorials linked above, you will execute a Gradle build. But what do you do if you’re given a Gradle build without any instructions?
Here are some useful steps to follow:
Determine whether the project has a Gradle wrapperВ and use it if it’s there — the main IDEs default to using the wrapper when it’s available.
Discover the project structure.
Either import the build with an IDE or run gradle projects from the command line. If only the root project is listed, it’s a single-project build. Otherwise it’s a multi-project build.
Find out what tasks you can run.
The help task can display extra information about a task, including which projects contain that task and what options the task supports.
Run the task that you are interested in.
From the command line, just run gradle to execute a particular task. You can learn more about command-line execution in the corresponding user manual chapter. If you’re using an IDE, check its documentation to find out how to run a task.
Gradle builds often follow standard conventions on project structure and tasks, so if you’re familiar with other builds of the same type — such as Java, Android or native builds — then the file and directory structure of the build should be familiar, as well as many of the tasks and project properties.
For more specialized builds or those with significant customizations, you should ideally have access to documentation on how to run the build and what build properties you can configure.
Authoring Gradle builds
Learning to create and maintain Gradle builds is a process, and one that takes a little time. We recommend that you start with the appropriate core plugins and their conventions for your project, and then gradually incorporate customizations as you learn more about the tool.
Here are some useful first steps on your journey to mastering Gradle:
Try one or two basic tutorials to see what a Gradle build looks like, particularly the ones that match the type of project you work with (Java, native, Android, etc.).
Learn about the fundamental elements of a Gradle build: projects, tasks, and the file API.
If you are building software for the JVM, be sure to read about the specifics of those types of projects in Building Java & JVM projects and Testing in Java & JVM projects.
Familiarize yourself with the core plugins that come packaged with Gradle, as they provide a lot of useful functionality out of the box.
The user manual contains a lot of other useful information and you can find samples demonstrating various Gradle features on the samples pages.
Integrating 3rd-party tools with Gradle
Gradle’s flexibility means that it readily works with other tools, such as those listed on our Gradle & Third-party Tools page.
There are two main modes of integration:
A tool drives Gradle — uses it to extract information about a build and run it — via the Tooling API
Gradle invokes or generates information for a tool via the 3rd-party tool’s APIs — this is usually done via plugins and custom task types
Tools that have existing Java-based APIs are generally straightforward to integrate. You can find many such integrations on Gradle’s plugin portal.
Getting Started with Gradle
In this tutorial, we’ll create a Gradle project, will run and test it, and run the executable JAR file using Gradle.
The project used in this tutorial can be found on GitHub.
Step 1. Create a project
Let’s create a Gradle project with Java.
Create a new Gradle Project with IntelliJ IDEA
On the page that opens, let’s specify our project’s name (FizzBuzz) and the location.
Let’s select the Java option, which is what we need for our project and Gradle since we are creating a Gradle project.
IntelliJ IDEA automatically adds a project SDK (JDK) in the JDK field. In our tutorial we use the open JDK 14 version.
You can change the selected JDK, IntelliJ IDEA will download the appropriate Gradle version. The only thing you need to have is the internet connection.
Let’s leave the default Groovy fro Gradle DSL and unselect the Add sample code option since we going to add our own code from scratch.
We can use the default information for ArtifactId which basically is the name of our project and leave the default information in the GroupId field.
After we’ve created our project and it finished indexing, let’s see what is inside:
IntelliJ IDEA creates a project with the build.gradle file including the following code:
As you can see, IntelliJ IDEA conveniently adds a test dependency. IntelliJ IDEA supports code completion inside the build.gradle file. So, if we decide to add more dependencies, IntelliJ IDEA will quickly locate their names and versions.
IntelliJ IDEA also creates the src folder with main and test subdirectories in the Project tool window.
IntelliJ IDEA enables the dedicated Gradle tool window with a liked project and its default tasks. We will use this window to run our tasks.
The Gradle settings in our project are used to store the information about the linked projects, Gradle JVM, and build actions. You can quickly access them from the Gradle tool window (click on the toolbar).
As you can see, the build and test actions are delegated to Gradle. Also, the Gradle wrapper was used to determine Gradle for our project.
The project structure ( Ctrl+Alt+Shift+S ) contains information about the project’s JDK and a language level used in the project.
Step 2. Add Java code
Now let’s create a Java application that outputs the first 100 FizzBuzz numbers.
Add a Java class to the Gradle project
In the Project tool window open the src folder.
Add the following code to the main FizzBuzzProcessor class:
Our application is ready. Now, let’s create the necessary tests for it.
Create a test class
Now open the created test class and add the following code:
Step 3. Run the application with Gradle
Let’s quickly run the application to see if it works.
Run main class from the editor
Open the main class FizzBuzzProcessor in the editor.
Check the result in the Run tool window.
Step 4. Run tests
Now, let’s run the test we’ve created.
Run tests in a Gradle project
We can run our test from the editor or from the Gradle tool window using the test task. We will use the editor.
Click in the gutter of the editor.
The result of the test will be displayed in the Run tool window.
If we change the default number in one of the tests, it will fail.
As you can see, the Run tool window displays information obout the failed test including the specific line of the code where the error occurred.
Step 5. Create an executable JAR file
Now let’s build our application to create an executable JAR file.
In the Project tool window, double click the build.gradle file to open it in the editor.
Add the following code:
In the Gradle tool window, open the project’s node, then the Tasks node and double-click the build task to run it.
IntelliJ IDEA creates the build directory that contains our JAR file.
Check the Run tool window for the results.
Note that the build task includes the test task that Gradle executes. So, if we make a mistake in one of our tests, the test task will fail and the build task will fail as well.
Step 6. Run the JAR file with Gradle
Now let’s tweak the build.gradle file a little bit more, so we can execute our JAR file in the Run anything window.
Run the JAR file
In the Project tool window, double click the build.gradle file to open it in the editor.
Let’s add id ‘application’ to the plugins section and the following code:
In the Gradle tool window, open the project’s node, then the Tasks node. We can see that Gradle added the distribution node. Open the node and double-click the assembleDist task to run it.
If we check the build directory now, we’ll see that IntelliJ IDEA created additional directories.
In the window that opens, enter the gradlew run command.
We should have the same result as when we ran the application in the IntelliJ IDEA editor.
Alternatively, you can execute the run task under the application node.
Building Java Projects with Gradle
This guide walks you through using Gradle to build a simple Java project.
What you’ll build
You’ll create a simple app and then build it using Gradle.
What you’ll need
About 15 minutes
A favorite text editor or IDE
How to complete this guide
Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.
To start from scratch, move on to Set up the project.
To skip the basics, do the following:
Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-gradle.git
cd into gs-gradle/initial
Set up the project
First you set up a Java project for Gradle to build. To keep the focus on Gradle, make the project as simple as possible for now.
Create the directory structure
Install Gradle
Now that you have a project that you can build with Gradle, you can install Gradle.
It’s highly recommended to use an installer:
Homebrew (brew install gradle)
As a last resort, if neither of these tools suit your needs, you can download the binaries from https://www.gradle.org/downloads. Only the binaries are required, so look for the link to gradle-version-bin.zip. (You can also choose gradle-version-all.zip to get the sources and documentation as well as the binaries.)
Unzip the file to your computer, and add the bin folder to your path.
To test the Gradle installation, run Gradle from the command-line:
If all goes well, you see a welcome message:
You now have Gradle installed.
Find out what Gradle can do
Now that Gradle is installed, see what it can do. Before you even create a build.gradle file for the project, you can ask it what tasks are available:
You should see a list of available tasks. Assuming you run Gradle in a folder that doesn’t already have a build.gradle file, you’ll see some very elementary tasks such as this:
Speaking of adding plugins, next you add a plugin that enables basic Java build functionality.
Build Java code
Starting simple, create a very basic build.gradle file in the
you created at the beginning of this guide. Give it just just one line:
This single line in the build configuration brings a significant amount of power. Run gradle tasks again, and you see new tasks added to the list, including tasks for building the project, creating JavaDoc, and running tests.
You’ll use the gradle build task frequently. This task compiles, tests, and assembles the code into a JAR file. You can run it like this:
After a few seconds, «BUILD SUCCESSFUL» indicates that the build has completed.
To see the results of the build effort, take a look in the build folder. Therein you’ll find several directories, including these three notable folders:
reports. Reports produced by the build (such as test reports).
libs. Assembled project libraries (usually JAR and/or WAR files).
At this point, the project doesn’t have any library dependencies, so there’s nothing in the dependency_cache folder.
The reports folder should contain a report of running unit tests on the project. Because the project doesn’t yet have any unit tests, that report will be uninteresting.
The libs folder should contain a JAR file that is named after the project’s folder. Further down, you’ll see how you can specify the name of the JAR and its version.
Declare dependencies
The simple Hello World sample is completely self-contained and does not depend on any additional libraries. Most applications, however, depend on external libraries to handle common and/or complex functionality.
For example, suppose that in addition to saying «Hello World!», you want the application to print the current date and time. You could use the date and time facilities in the native Java libraries, but you can make things more interesting by using the Joda Time libraries.
First, change HelloWorld.java to look like this:
Here HelloWorld uses Joda Time’s LocalTime class to get and print the current time.
If you ran gradle build to build the project now, the build would fail because you have not declared Joda Time as a compile dependency in the build.
For starters, you need to add a source for 3rd party libraries.
The repositories block indicates that the build should resolve its dependencies from the Maven Central repository. Gradle leans heavily on many conventions and facilities established by the Maven build tool, including the option of using Maven Central as a source of library dependencies.
Now that we’re ready for 3rd party libraries, let’s declare some.
With the dependencies block, you declare a single dependency for Joda Time. Specifically, you’re asking for (reading right to left) version 2.2 of the joda-time library, in the joda-time group.
Another thing to note about this dependency is that it is a compile dependency, indicating that it should be available during compile-time (and if you were building a WAR file, included in the /WEB-INF/libs folder of the WAR). Other notable types of dependencies include:
Finally, let’s specify the name for our JAR artifact.
Build your project with Gradle Wrapper
The Gradle Wrapper is the preferred way of starting a Gradle build. It consists of a batch script for Windows and a shell script for OS X and Linux. These scripts allow you to run a Gradle build without requiring that Gradle be installed on your system. This used to be something added to your build file, but it’s been folded into Gradle, so there is no longer any need. Instead, you simply use the following command.
After this task completes, you will notice a few new files. The two scripts are in the root of the folder, while the wrapper jar and properties files have been added to a new gradle/wrapper folder.
The Gradle Wrapper is now available for building your project. Add it to your version control system, and everyone that clones your project can build it just the same. It can be used in the exact same way as an installed version of Gradle. Run the wrapper script to perform the build task, just like you did previously:
The first time you run the wrapper for a specified version of Gradle, it downloads and caches the Gradle binaries for that version. The Gradle Wrapper files are designed to be committed to source control so that anyone can build the project without having to first install and configure a specific version of Gradle.
At this stage, you will have built your code. You can see the results here:
The class files are bundled up. It’s important to note, that even though you declared joda-time as a dependency, the library isn’t included here. And the JAR file isn’t runnable either.
To make this code runnable, we can use gradle’s application plugin. Add this to your build.gradle file.
Then you can run the app!
To bundle up dependencies requires more thought. For example, if we were building a WAR file, a format commonly associated with packing in 3rd party dependencies, we could use gradle’s WAR plugin. If you are using Spring Boot and want a runnable JAR file, the spring-boot-gradle-plugin is quite handy. At this stage, gradle doesn’t know enough about your system to make a choice. But for now, this should be enough to get started using gradle.
To wrap things up for this guide, here is the completed build.gradle file:
There are many start/end comments embedded here. This makes it possible to extract bits of the build file into this guide for the detailed explanations above. You don’t need them in your production build file. |
Summary
Congratulations! You have now created a simple yet effective Gradle build file for building Java projects.
See Also
The following guide may also be helpful:
Want to write a new guide or contribute to an existing one? Check out our contribution guidelines.
All guides are released with an ASLv2 license for the code, and an Attribution, NoDerivatives creative commons license for the writing. |
Get the Code
Table of contents
Get ahead
VMware offers training and certification to turbo-charge your progress.
Get support
Spring Runtime offers support and binaries for OpenJDK™, Spring, and Apache Tomcat® in one simple subscription.
Upcoming events
Check out all the upcoming events in the Spring community.