Groovy in a Gradle build

Gradle is written in Groovy, embeds a Groovy runtime, and compiles a Groovy source folder with no plugin from a repository. A project that already uses Gradle needs three lines to run Groovy code, and this lesson shows the run.

The project

The build script applies the plugins groovy and application, takes the Groovy runtime of Gradle itself through localGroovy() in the dependencies block, and names the script in application { mainClass = 'greet' }. Nothing is downloaded, which is what makes the build work with no network. The Groovy DSL lesson of the Gradle course reads the four blocks of that file line by line, and this page does not repeat them.

The source folder is src/main/groovy, and a script of that folder compiles to a class named after its file, which is why mainClass = 'greet' names the script:

src/main/groovy/greet.groovy

println "Hello, ${args ? args[0] : 'Groovy'}"

Run it

The image runs Gradle offline, without the daemon and with a plain console, which are the flags the Gradle course explains. The task line, the program output and the build result are the real ones; the welcome banner and the build time are left out.

gradle run --args=World --offline --no-daemon --console=plain

> Task :compileJava NO-SOURCE
> Task :compileGroovy
> Task :processResources NO-SOURCE
> Task :classes
> Task :run
Hello, World
BUILD SUCCESSFUL in 18s
2 actionable tasks: 2 executed

compileGroovy compiled the script with the Groovy of the Gradle installation, and run started the class with the arguments of --args. Without an argument the script prints its default, which is the second half of its first line.

Spock in a build

A test dependency on Spock is declared like any other in the dependencies block (testImplementation 'org.spockframework:spock-core:2.4-groovy-5.0'), and the test task needs useJUnitPlatform(). This image has no repository with that artifact, so this build is not run here: the specifications of the Spock lessons run through the JUnit launcher and the jars in /opt/spock instead. The Groovy and Spock lesson of the Gradle course shows the block in a build, with the failure this image gets.

Related

Article author: Arthur Isaev

Banner image