Web Applications with Grails and Micronaut
Prerequisites: Runtime metaprogramming, Testing with Spock
Two frameworks let you build web applications and services in Groovy.
Grails
Grails is a full-stack web framework built on Spring Boot, now an Apache project. It follows "convention over configuration", inspired by Ruby on Rails: put a class in the right folder and Grails knows what it is.
// illustrative — grails-app/domain/shop/Book.groovy
package shop
class Book {
String title
String author
BigDecimal price
Date dateCreated
static constraints = {
title blank: false, maxSize: 200
price min: 0.0
}
}
// illustrative — grails-app/controllers/shop/BookController.groovy
package shop
class BookController {
static responseFormats = ['json']
def index(Integer max) {
respond Book.list(max: Math.min(max ?: 10, 100), sort: 'title')
}
def show(Long id) {
respond Book.get(id)
}
def byAuthor(String author) {
respond Book.findAllByAuthorIlike("%${author}%")
}
}
- Domain classes are persisted with GORM (Grails' data layer,
on Hibernate or MongoDB). Methods like
list,get,save, and dynamic finders such asfindAllByAuthorIlikeare added at runtime — the metaprogramming from Level 3's first lesson. static constraintsis a DSL for validation rules.- Controllers map to URLs by convention (
/book/show/1) or throughUrlMappings. - Commands:
grails create-app,grails create-domain-class,./gradlew bootRun. Grails apps are tested with Spock.
Micronaut
Micronaut is a JVM framework for microservices and serverless functions that supports Java, Kotlin, and Groovy. Instead of runtime reflection, it does dependency injection and routing at compile time (using AST transformations in Groovy), so apps start fast and use little memory.
// illustrative — src/main/groovy/shop/GreetingController.groovy
package shop
import groovy.transform.CompileStatic
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import jakarta.inject.Singleton
@Singleton
class GreetingService {
String greet(String name) { "Hello, $name!" }
}
@CompileStatic
@Controller('/greet')
class GreetingController {
private final GreetingService service
GreetingController(GreetingService service) { this.service = service }
@Get('/{name}')
Map<String, String> greet(String name) {
[message: service.greet(name)]
}
}
$ curl http://localhost:8080/greet/Ada
{"message":"Hello, Ada!"}
Create projects at micronaut.io/launch (choose Groovy as the
language) or with the mn CLI.
Which to choose
| Grails | Micronaut | |
|---|---|---|
| Style | Full-stack, conventions, GORM, views | Lean services and APIs |
| Start-up | Spring Boot speed | Very fast, low memory; GraalVM native |
| Groovy usage | Dynamic Groovy throughout | Often @CompileStatic |
| Good for | CRUD-heavy web apps, admin tools | Microservices, serverless |
Spring Boot itself also works with Groovy classes if your team already uses Spring.