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' repositories.mavenCentral() // New configuration for CXF dependencies. configurations { cxf } ext { // CXF version. cxfVersion = '2.6.2' // Artifacts for CXF dependency. cxfArtifacts = [ 'cxf-tools-wsdlto-frontend-jaxws', 'cxf-tools-wsdlto-databinding-jaxb', 'cxf-tools-common', 'cxf-tools-wsdlto-core' ] } 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