Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 38 ยท Build Tools and Ecosystem

Groovy with Java and Spring

Mix Groovy and Java in one project: joint compilation in Gradle, calling each way, GroovyShell and scripting, Spring Boot with Groovy, Micronaut, Grails and Jenkins.

Groovy compiles to ordinary JVM bytecode, so a Groovy class is a Java class and the other way round. There is no bridge or foreign-function layer. This makes Groovy an easy addition to an existing Java codebase: write tests in Spock, scripts in Groovy, or whole modules where its concise syntax pays off, and keep the rest in Java.

Groovy cannot run on this site, so Groovy code is read-only. The Java stand-ins show the pieces that are plain Java: evaluating a script string through the JDK scripting API and calling code through reflection.

Calling Java from Groovy

Everything in the Java platform is available: java.util, java.time, any library on the classpath.

GROOVY
import java.time.LocalDate
import java.util.concurrent.ConcurrentHashMap

def cache = new ConcurrentHashMap<String, Integer>()
cache.put("a", 1)
println LocalDate.of(2025, 1, 31).plusMonths(1)    // 2025-02-28

Groovy adds helper methods to Java classes (the GDK): list.collect {}, file.text, str.padLeft(5). Java classes remain unchanged.

Calling Groovy from Java

A compiled Groovy class is a normal class. Properties become getters and setters:

GROOVY
// src/main/groovy/com/example/Person.groovy
package com.example

class Person {
  String name
  int age
  String greet() { "Hi, I am ${name}" }
}
Java
// src/main/java/com/example/App.java
package com.example;

public class App {
  public static void main(String[] args) {
    Person p = new Person();
    p.setName("Ada");
    p.setAge(36);
    System.out.println(p.greet());
  }
}

The Java code uses setName, which the Groovy compiler generated. Dynamic features such as methodMissing are not visible to Java, because javac checks at compile time.

Joint compilation

The two languages can refer to each other in one module. Gradle's Groovy plugin handles it:

GROOVY
plugins {
  id 'groovy'
}

sourceSets {
  main {
    groovy {
      srcDirs = ['src/main/groovy', 'src/main/java']   // joint compilation
    }
    java {
      srcDirs = []
    }
  }
}

With this setup, Groovy's compiler also compiles the Java files in src/main/java, creating stubs so both directions resolve. The alternative is to keep Java and Groovy in separate modules with a one-way dependency, which is faster and tidier for big projects. Maven works with the GMavenPlus plugin.

Evaluating Groovy text at runtime

Embedding Groovy as a scripting layer for rules or configuration is common:

GROOVY
def binding = new Binding([price: 100, vip: true])
def shell = new GroovyShell(binding)
def discount = shell.evaluate("vip ? price * 0.9 : price")
println discount    // 90.0

From Java you can use GroovyShell, the JSR-223 ScriptEngineManager().getEngineByName("groovy"), or GroovyClassLoader to load a class from source.

Evaluating text means executing code with your privileges. Never evaluate scripts from untrusted users. If you need user-provided rules, use SecureASTCustomizer in a CompilerConfiguration to restrict allowed syntax, run in a sandboxed process, or choose a restricted expression language.

Groovy in frameworks

Framework What Groovy gives you
Spring / Spring Boot Groovy beans and configuration (beans { } DSL), Spring Boot CLI with scripts, Spock tests with @SpringBean
Grails A full-stack web framework on Spring Boot, with GORM for data access, convention over configuration
Micronaut Compile-time DI, Groovy supported as a language, Spock tests
Ratpack A reactive HTTP toolkit with a Groovy DSL
Gradle Build scripts and plugins
Jenkins Pipeline files (Jenkinsfile) are Groovy, using a restricted sandbox
SoapUI, Katalon, Geb Test automation scripts
Apache Camel, Griffon, Vert.x Routes, desktop apps and event-driven services with Groovy DSLs

A small Spring Boot controller in Groovy

GROOVY
@RestController
class HelloController {
  @GetMapping("/hello")
  Map hello(@RequestParam(defaultValue = "world") String name) {
    [message: "Hello, ${name}!"]
  }
}

Spring serializes the returned Map to JSON. Properties instead of getters, GString interpolation, and map literals shorten the code compared with Java.

When to choose Groovy over Java

  • Scripts, build logic and test code (Spock is the main reason many Java teams adopt it).
  • DSLs and configuration that non-programmers read.
  • Prototypes, data wrangling and glue code.
  • Choose Java or Kotlin when you need maximum static checking, strong tooling in big teams, or best raw performance. @CompileStatic narrows the gap but does not remove dynamic-typing trade-offs.

Try it: evaluating script text with the JDK (stand-in)

Java has no Groovy engine built in, so this stand-in evaluates a small arithmetic expression with a hand-made evaluator, using a binding, just like GroovyShell.evaluate.

Java Stand-in: a tiny evaluator with a binding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: properties become getters and setters (stand-in)

The Java class below is what the Groovy Person compiles to: private fields plus generated accessors. Java code calls them as usual.

Java Stand-in: what the Groovy compiler generates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can Java code call a Groovy class directly?

    Groovy compiles to normal .class files, so the JVM sees no difference between the languages.
  2. 2. What does a Groovy property String name become in bytecode?

    Groovy generates the accessor methods, which Java callers use.
  3. 3. Why is evaluating user-supplied Groovy text dangerous?

    A script can do anything your program can do, unless you restrict it with a sandbox.
  4. 4. What is joint compilation?

    The Groovy compiler generates stubs for Java files so both directions of references resolve.

Summary

  • Groovy and Java share the JVM, so they call each other with no bridge.
  • Groovy properties generate getters and setters for Java callers; dynamic features stay invisible to Java.
  • Gradle's groovy plugin supports joint compilation; separate modules are tidier for large projects.
  • GroovyShell and JSR-223 embed Groovy scripting, which must be sandboxed for untrusted input.
  • Groovy appears in Spring, Grails, Micronaut, Gradle, Jenkins and test tools.

Next: Project: A Command-Line To-Do Manager