This tutorials shows a quick getting started example of Gradle.
What is Gradle?
- Gradle is a build automation tool.
- It provides its own Groovy-based domain language (DSL) instead of XML for its build scripts.
- As opposed to Maven's rigid model, Gradle is very flexible and can be extended easily.
- Gradle is considered to be faster than Maven. It tracks source file changes and processes only what is necessary. It also uses build cache and keeps build information in runtime memory to improve the performance.
- Like Maven, Gradle also provides a dependency management system. It downloads the dependent jars, saves and reuse them from local cache (USER_HOME/.gradle folder).
- Like Maven, Gradle also provides convention over configuration.
- Gradle comes with various built-in plugins. A custom plugin can also be built in any JVM based language. A Gradle plugin is a group of tasks.
Installing Gradle
Gradle can be download via various methods. I prefer to download zip package from here. I chose 'Complete, with docs and sources' option (instead of 'Binary-only') because that helps in Intellij (even in community edition) to see Gradle's documents and source code. After downloading, unzip the package (gradle-4.10.2-all.zip) anywhere and set the bin folder in system path (D:\gradle-4.10.2-all\gradle-4.10.2\bin). JAVA_HOME environmental variable should also be set. I am using JDK 9.
Checking the installation:
C:>gradle -v
------------------------------------------------------------ Gradle 4.10.2 ------------------------------------------------------------
Build time: 2018-09-19 18:10:15 UTC Revision: b4d8d5d170bb4ba516e88d7fe5647e2323d791dd
Kotlin DSL: 1.0-rc-6 Kotlin: 1.2.61 Groovy: 2.4.15 Ant: Apache Ant(TM) version 1.9.11 compiled on March 23 2018 JVM: 11 (Oracle Corporation 11+28) OS: Windows 10 10.0 amd64
WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/D:/gradle/gradle-4.10.2-bin/gradle-4.10.2/lib/groovy-all-2.4.15.jar) to method java.lang.Object.finalize() WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release
The warning shown at the end are due to Java 9 modules changes. To fix this warning set following in D:\gradle-4.10.2\bin\gradle.bat (gradle issue #2995) :
set JAVA_OPTS=--add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED
Check again:
C:>gradle -v
------------------------------------------------------------ Gradle 4.10.2 ------------------------------------------------------------
Build time: 2018-09-19 18:10:15 UTC Revision: b4d8d5d170bb4ba516e88d7fe5647e2323d791dd
Kotlin DSL: 1.0-rc-6 Kotlin: 1.2.61 Groovy: 2.4.15 Ant: Apache Ant(TM) version 1.9.11 compiled on March 23 2018 JVM: 11 (Oracle Corporation 11+28) OS: Windows 10 10.0 amd64
Example
In this example we are going to create a Java project. Let's create a directory at D:\gradle-getting-started-example and add build.gradle file (this is the main gradle file where we do all configuration)
build.gradleapply plugin: "java"
Quick understanding of Gradle DSL
Above line is written in Groovy language but the 'apply' part is defined by Gradle DSL API. It's better to understand a little how groovy works. Above line is nothing but a method call equivalent to the following:
apply(plugin: "java")
Where the method parameter plugin:"java" is equivalent to java.util.Map with key=plugin and value=java. Groovy is built on Java. It removes a lot of boilerplate code, so instead of the above code following code will work as well:
apply(Map.of("plugin", "java"));
In Gradle DSL, Project interface is the main API which we will be interacting with. The whole script written in build.gradle file represents an instance of Project interface. We also has an implicit variable 'project' (the root instance of Project interface) which can be used as:
project.apply(plugin: "java")
Whatever construct we are going to use in build.gradle file, a corresponding method/property/closure can be found in Project interface doc. Above function call (doc) enables Java Plugin. The value="Java" is nothing but a plugin id. According to the document we can also use the class of an implementation of Plugin instead of its id. So in our example:
apply plugin: JavaPlugin.class
The list of standard plugins along with their ids can be found here The details of Java Plugin can be found here. .
Creating Java Project structure
Java Plugin expects the following directory layout by default (maven style directory structure):
- Java source code: src/main/java
- Classpath resources files: src/main/resources
- Test Java source code: src/test/java
- Test resources: src/test/resources
More details can be found here.
Let's continue with our example and create the necessary directories. In this example we will only focus on a Java class accessing a classpath resource.
After creating directories we have following structure
D:\gradle-getting-started-example>tree /a /f Folder PATH listing for volume Data Volume serial number is 68F9-EDFA D:. | build.gradle | \---src \---main +---java \---resources
Let's now add a Java Class and a resource file.
Example Java class
gradle-getting-started-example/src/main/java/com/logicbig/example/ExampleMain.javapackage com.logicbig.example;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Properties;
public class ExampleMain {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(ExampleMain.class.getResourceAsStream("/msg.properties"));
System.out.println("msg: " + properties.get("msg"));
System.out.println("date time now: " + LocalDateTime.now());
}
}
Example resource file
src/main/resources/msg.propertiesmsg=hello gradle
Building project
The command gradle build is used to build a project:
D:\gradle-getting-started-example>gradle build Starting a Gradle Daemon (subsequent builds will be faster) > Task :compileJava > Task :processResources > Task :classes > Task :jar > Task :assemble > Task :compileTestJava NO-SOURCE > Task :processTestResources NO-SOURCE > Task :testClasses UP-TO-DATE > Task :test NO-SOURCE > Task :check UP-TO-DATE > Task :build
BUILD SUCCESSFUL in 4s 3 actionable tasks: 3 executed
Above build creates two folders .gradle and build. We have this directory structure now:
D:\gradle-getting-started-example>tree /a /f Folder PATH listing for volume Data Volume serial number is 68F9-EDFA D:. | build.gradle | +---.gradle | +---4.10.2 | | | gc.properties | | | | | +---fileChanges | | | last-build.bin | | | | | +---fileContent | | | fileContent.lock | | | | | +---fileHashes | | | fileHashes.bin | | | fileHashes.lock | | | | | +---javaCompile | | | javaCompile.lock | | | taskHistory.bin | | | | | +---taskHistory | | | taskHistory.bin | | | taskHistory.lock | | | | | \---vcsMetadata-1 | +---buildOutputCleanup | | buildOutputCleanup.lock | | cache.properties | | outputFiles.bin | | | \---vcs-1 | gc.properties | +---build | +---classes | | \---java | | \---main | | \---com | | \---logicbig | | \---example | | ExampleMain.class | | | +---libs | | gradle-getting-started-example.jar | | | +---resources | | \---main | | msg.properties | | | \---tmp | +---compileJava | \---jar | MANIFEST.MF | \---src \---main +---java | \---com | \---logicbig | \---example | ExampleMain.java | \---resources msg.properties
We will not be interacting with .gradle folder, because everything there is for Gradle internal working.
Running
Gradle build has also created the jar file under build\libs folder. Let's run it:
D:\gradle-getting-started-example>java -cp build\libs\gradle-getting-started-example.jar com.logicbig.example.ExampleMain msg: hello gradle date time now: 2018-11-04T02:17:04.231790900
Gradle help
D:\gradle-getting-started-example>gradle help
> Task :help
Welcome to Gradle 4.10.2.
To run a build, run gradle <task> ...
To see a list of available tasks, run gradle tasks
To see a list of command-line options, run gradle --help
To see more detail about a task, run gradle help --task <task>
For troubleshooting, visit https://help.gradle.org
BUILD SUCCESSFUL in 0s 1 actionable task: 1 executed
D:\gradle-getting-started-example>gradle tasks
> Task :tasks
------------------------------------------------------------ All tasks runnable from root project ------------------------------------------------------------
Build tasks ----------- assemble - Assembles the outputs of this project. build - Assembles and tests this project. buildDependents - Assembles and tests this project and all projects that depend on it. buildNeeded - Assembles and tests this project and all projects it depends on. classes - Assembles main classes. clean - Deletes the build directory. jar - Assembles a jar archive containing the main classes. testClasses - Assembles test classes.
Build Setup tasks ----------------- init - Initializes a new Gradle build. wrapper - Generates Gradle wrapper files.
Documentation tasks ------------------- javadoc - Generates Javadoc API documentation for the main source code.
Help tasks ---------- buildEnvironment - Displays all buildscript dependencies declared in root project 'gradle-getting-started-example'. components - Displays the components produced by root project 'gradle-getting-started-example'. [incubating] dependencies - Displays all dependencies declared in root project 'gradle-getting-started-example'. dependencyInsight - Displays the insight into a specific dependency in root project 'gradle-getting-started-example'. dependentComponents - Displays the dependent components of components in root project 'gradle-getting-started-example'. [incubating] help - Displays a help message. model - Displays the configuration model of root project 'gradle-getting-started-example'. [incubating] projects - Displays the sub-projects of root project 'gradle-getting-started-example'. properties - Displays the properties of root project 'gradle-getting-started-example'. tasks - Displays the tasks runnable from root project 'gradle-getting-started-example'.
Verification tasks ------------------ check - Runs all checks. test - Runs the unit tests.
Rules ----- Pattern: clean<TaskName>: Cleans the output files of a task. Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration. Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration.
To see all tasks and more detail, run gradle tasks --all
To see more detail about a task, run gradle help --task <task>
BUILD SUCCESSFUL in 0s 1 actionable task: 1 executed
Most of the tasks as shown above, come from the plugin which we have applied, in our example that plugin is Java Plugin.
If we execute gradle tasks in an empty folder (without a build.gradle at all) then:
D:\gradle-empty>tree Folder PATH listing for volume Data Volume serial number is 68F9-EDFA D:. No subfolders exist
D:\gradle-empty>gradle tasks
> Task :tasks
------------------------------------------------------------ All tasks runnable from root project ------------------------------------------------------------
Build Setup tasks ----------------- init - Initializes a new Gradle build. wrapper - Generates Gradle wrapper files.
Help tasks ---------- buildEnvironment - Displays all buildscript dependencies declared in root project 'gradle-empty'. components - Displays the components produced by root project 'gradle-empty'. [incubating] dependencies - Displays all dependencies declared in root project 'gradle-empty'. dependencyInsight - Displays the insight into a specific dependency in root project 'gradle-empty'. dependentComponents - Displays the dependent components of components in root project 'gradle-empty'. [incubating] help - Displays a help message. model - Displays the configuration model of root project 'gradle-empty'. [incubating] projects - Displays the sub-projects of root project 'gradle-empty'. properties - Displays the properties of root project 'gradle-empty'. tasks - Displays the tasks runnable from root project 'gradle-empty'.
To see all tasks and more detail, run gradle tasks --all
To see more detail about a task, run gradle help --task <task>
BUILD SUCCESSFUL in 0s 1 actionable task: 1 executed
Running above command, even in an empty folder, has already created '.gradle' folder:
D:\gradle-empty>dir /b .gradle
Example ProjectDependencies and Technologies Used: |