October 22, 2012

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.