Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Gradle Goodness: Running Java Tasks With Gradle

DZone's Guide to

Gradle Goodness: Running Java Tasks With Gradle

Learn how to pass Java system properties to Java tasks using the open source Gradle build tool.

· DevOps Zone ·
Free Resource

Can you release faster without sacrificing quality? See how with our free ebook Strategies for a Successful Test Automation Project and a free trial of Ranorex Studio today!

Gradle is of course a great build tool for Java related projects. If we have tasks in our projects that need to execute a Java application we can use theJavaExec task. When we need to pass Java system properties to the Java application we can set the systemProperties property of the JavaExectask. We can assign a value to the systemProperties property or use the method systemProperties that will add the properties to the existing properties already assigned. Now if we want to define the system properties from the command-line when we run Gradle we must pass along the properties to the task. Therefore we must reconfigure a JavaExec task and assign System.properties to the systemProperties property.

In the following build script we reconfigure all JavaExec tasks in the project. We use the systemProperties method and use the valueSystem.properties. This means any system properties from the command-line are passed on to the JavaExec task.

apply plugin: 'groovy'
apply plugin: 'application'

mainClassName = 'com.mrhaki.sample.Application'

repositories.jcenter()

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.4'
}

// The run task added by the application plugin
// is also of type JavaExec.
tasks.withType(JavaExec) {
    // Assign all Java system properties from 
    // the command line to the JavaExec task.
    systemProperties System.properties
}

We write a simple Groovy application that uses a Java system property app.greeting to print a message to the console:

// File: src/main/groovy/com/mrhaki/sample/Application.groovy
package com.mrhaki.sample

println "Hello ${System.properties['app.greeting']}"

Now when we execute the run task (of type JavaExec) and define the Java system property app.greeting in our command it is used by the application:

$ gradle -Dapp.greeting=Gradle! -q run


Hello Gradle!

Written with Gradle 2.7.

Get your test automation project off to the right start. Download your free test planning template and a 30-day no-obligation trial of Ranorex Studio today!

Topics:
devops ,java ,gradle ,build

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}