Gradle Build Tool – Guide

Gradle Build Tool is an open source, advanced general purpose build management system. It is built on ANT, Maven, and lvy repositories. It supports Groovy based Domain Specific Language (DSL) over XML.

Gradle handles two major things using its build script – one the project build and the other is tasks.

A Task – means small chunk of work which the build performs and a project is made of many tasks, examples : creating a jar package, compiling files or any other target like in ANT build xml file.

Build a gradle script

Gradle used groovy language to make build scripts, it follows UTF-8 standard

File name : build.gradle

Sample script to run a task

 
 task print {
            doLast {
            println 'ProgrammerToday'
                    }
            }
        	

Execute the script : C:\> gradle -q print

To build source files from other folder

Do the following in the build script, for example if the folder name is src instead of the usual src/main/java

 
apply plugin: 'java'
sourceSets {
    main {
      java {
          srcDir 'src'
      }
    }
  
    test {
      java {
          srcDir 'test'
      }
    }
}
        

Adding dependencies in the gradle build file

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.12'
    testCompile 'junit:junit:4.12'
}
        

To run a main class from the build file

Assuming there is a class Test with a main method

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.12'
    testCompile 'junit:junit:4.12'
}

jar {
    manifest {
      attributes 'Main-Class': 'com.gradle.main.Application'
    }
}
        
To compile the above code

dir\> gradle tasks
dir\> gradle assemble
dir\> gradle build

Gradle installation | prerequisites

Steps to install gradle :

  1. Install and set the environment variables
  2. Install gradle and set the environment variables
    GRADLE_HOME & PATH just as in for jdk
  3. Verify the gradle installation
    C:\gradle -v

Summary

In this tutorial we saw how to use Gradle as a build tool, how to create a gradle build script, how to add dependencies in gradle build file, we learnt how to run a main class file from the gradle build file and its installation.
Hope you liked it !


Leave a Comment