Print Shortlink

Gradle your Java app

Working with ANT has always been a slightly boring experience for me because of it’s rigid XML syntax. Setting up classpath, tasks like clean, compile, run tests etc., every time is a tedious process.
Ever since I started working with Groovy I started looking at a build tool known as Gradle. Gradle is a Groovy script that can be used to automate the build activities of your project. Let’s see how to build a simple Java project using Gradle.

You can download Gradle and add the bin folder to the path. I have a simple project ‘GradleEx1″ with the following project structure.

The src folder will have a class Hello with the following code.

package com.durasoft;
public class Hello{
	public String sayHello(String name){
		return "Hello " + name;	
	}
}

The tests folder will have a test case HelloTest with the following code.

package com.durasoft;

import org.junit.* ;
import static org.junit.Assert.* ;

public class HelloTest{

	private Hello helloObj = new Hello();
	
	@Test
	public void testSayHello(){
		assertEquals(helloObj.sayHello("Sam"),"Hello Sam");
	}
}

Let’s create a build script build.gradle in the GradleEx1 folder. This gradle file will have a groovy script where you will specify the tasks compile, run tests and package them in a jar file. While doing that you will also add reference to JUnit library.

The build.gradle file is shown below.

apply plugin:'java'

version = "1.0"

repositories {
  mavenCentral()
}
 
dependencies {
  testCompile group: 'junit', name: 'junit', version: '4.8+'
}

sourceSets {
	main {
		java {
			srcDir "src"
		}
	}
	test {
		java {
			srcDir "tests"
		}
	}
}

Is that all??? Yes. All I have done is specify the source folders and the dependencies from maven repository. So what about the compile, run tests, jar etc? The single line apply plugin:’java’ does the trick. It gives you built-in tasks like compileJava, test, jar etc., associated with any ANT build. Here’s where the ‘convention over configuration’ paradigm of Groovy/Grails comes into picture.

So how do we run this? Go to command prompt and run gradle test from GradleEx1 folder.

You can also run gradle jar to create GradleEx1-1.0.jar file. Have a look at the build folder generated in GradleEx1 folder.
Gradle is pretty simple and straightforward and makes use of the DSL capability of Groovy. It’s definitely a welcome change in configuring builds.

Page 1 of 1

One Response

  1. Gnanasuriyan

    Now I get the purpose of Gradle.

    -Thanks

Leave a Reply