Tuesday, March 8, 2011

Getting Started with Gradle

As a build tool, Gradle has a pretty steep learning curve. The official documentation is a good place to start.

build.gradle
apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'eclipse'

version = '1.0'

repositories {
    mavenCentral()   
    flatDir name: 'localRepository', dirs: 'lib'
}

dependencies {
    runtime group: 'log4j', name: 'log4j', version: '1.2.+'  
    compile ':junit:4.0'
}

task hello << {
    println System.properties['msg']
    ant.echo('Hello')
}

compileJava.dependsOn(hello)

gradle.properties
systemProp.http.proxyHost=myhost
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.msg

Project structure
gradle-project/src/main/java/MyJava.java 
               src/main/resources/
               src/main/groovy/MyGroovy.groovy
               src/test/java/MyJavaTest.java
               src/test/groovy/MyGroovy.grovy
               src/test/resources/
               build.gradle
               gradle.properties   
              /lib/junit-4.0.jar               

Here, we use Java, Groovy, and Eclipse plugins. With Java plugin, the conventional project structure is defined as below.
src/main/java
src/main/resources
src/test/java
src/test/resources

With Groovy plugin, the conventional project structure is defined as below.
src/main/groovy
src/main/resources
src/test/groovy
src/test/resources
As you can see here, it's very easy to mix between Java and Groovy projects. Gradle also supports another language such as Scala.

To generate Eclipse project:
gradle eclipse
To clean the generated Eclipse project
gradle cleanEclipse

To build the project:
gradle build
This will compile Java and Groovy files.

To clean the project:
gradle clean

As we can see here, it's pretty easy create a custom hello task and make it as a dependency of an existing compileJavaTask as shown in the example above. Because Gradle is based on Groovy, we can leverage on Groovy programming language and Groovy out of the box supports Ant.

To execute the individual task:
gradle hello

To view the list of available tasks:
gradle tasks

With Gradle, it's easy to mix dependency management between Maven and local repository as shown in the example above.

There are still so many things that Gradle can provide, but hopefully this simple tutorial is sufficient to get started with Gradle.

No comments:

Post a Comment