May 25, 2021 Gradle
To build a Groovy project, you need to use the Groovy plug-in. T he plug-in extends the Java plug-in and adds Groovy's compilation capabilities to your project. Y our project can contain Groovy source code, Java source code, or both. I n other respects, the Groovy project is almost identical to the Java project we saw in Chapter 7 Java Quick Start.
Let's look at an example. T o use the Groovy plug-in, you need to add the following to the build script file:
Example Groovy plugin
build.gradle
apply plugin: 'groovy'
Note: The code for this example can be seen in Gradle's
samples/groovy/quickstart
the source code.
This code also applies the Java plug-in to the project if the Java plug-in has not been applied. T
he Groovy plug-in inherits the compile task, looks for the source file in the
src/main/groovy
and inherits the compileTest task to find the source file of the test in the
src/test/groovy
directory. T
hese compilation tasks use federation compilation for these directories, which means that they can contain both java and groovy source files.
To compile a task with groovy, you must also declare which version of Groovy to use and where to get the Groovy library. Y ou can do this by adding dependencies to the groovy configuration. T he compile configuration inherits this dependency so that when the Groovy and Java source codes are compiled, the groovy library is also included in the class path. I n the following example, we'll use the Groovy 2.2.0 version in Maven's central repository.
Example Dependency on Groovy 2.2.0
build.gradle
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.2.0'
}
Here's the build file we wrote:
Example Groovy example - complete build file
build.gradle
apply plugin: 'eclipse'
apply plugin: 'groovy'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.2.0'
testCompile 'junit:junit:4.11'
}
Running the gradle build will compile, test, and package your project into jar.
This chapter describes a very simple Groovy project. O ften, a real project requires more than that. B ecause a Groovy project is also a Java project, because the Groovy project is also a Java project, you can do what Groovy can do with Java.
You can refer to the Groovy plug-in to learn more about the Groovy plug-in, or find more examples of Groovy projects in the samples/groovy directory of the Gradle distribution package.