Monday, October 22, 2012

Gradle Goodness: Running Java Applications from External Dependency

With Gradle we can execute Java applications using the JavaExec task or the javaexec() method. If we want to run Java code from an external dependency we must first pull in the dependency with the Java application code. The best way to do this is to create a new dependency configuration. When we configure a task with type JavaExec we can set the classpath to the external dependency. Notice we cannot use the buildscript{} script block to set the classpath. A JavaExec task will fork a new Java process so any classpath settings via buildscript{} are ignored.

In the following example build script we want to execute the Java class org.apache.cxf.tools.wsdlto.WSDLToJava from Apache CXF to generate Java classes from a given WSDL. We define a new dependency configuration with the name cxf and use it to assign the CXF dependencies to it. We use the classpath property of the JavaExec task to assign the configuration dependency.

// File: build.gradle

// Base plugin for task rule clean<task>
apply plugin: 'base'


// New configuration for CXF dependencies.
configurations { cxf }

ext {
    // CXF version.
    cxfVersion = '2.6.2'

    // Artifacts for CXF dependency.
    cxfArtifacts = [

dependencies {
    // Assign CXF dependencies to configuration.
    cxfArtifacts.each { artifact ->
        cxf "org.apache.cxf:$artifact:$cxfVersion"

// Custom task to generate Java classes
// from WSDL.
task wsdl2java(type: JavaExec) {
    ext {
        wsdlFile = 'src/wsdl/service-contract.wsdl'
        outputDir = file("$buildDir/generated/cxf")

    inputs.file file(wsdlFile)
    outputs.dir outputDir

    // Main Java class to invoke.
    main = 'org.apache.cxf.tools.wsdlto.WSDLToJava'

    // Set classpath to dependencies assigned
    // to the cxf configuration.
    classpath = configurations.cxf

    // Arguments to be passed to WSDLToJava.
    args '-d', outputDir
    args '-client'
    args '-verbose'
    args '-validate'
    args wsdlFile

Code written with Gradle 1.2


Md.Fazlul Bari said...

Visit our website
java training that is the largest professional java training site where java,
java training, online java course, java training in Virginia,
java programming are available

more detail.......
online java course
java programming
java training in Virginia

vijay said...

NICE BLOG!!! Thanks for sharing useful information about FNT Softwre Solutions and being one of best Software Training institute in Bangalore we agree that this blog is very useful for the students who are searching for best software courses, I would really like to come back again right here for like wise good articles or blog posts. Thanks for sharing...Java training company bangalore.

shwetha hariharan said...

Thanks a ton Really helpful..

Java Course

Post a Comment