login

GuicyGroovlets

Groovlets with Guice

One of the really useful things that Groovlets can do is access your existing service layer via your Dependency Injector. Although you can get Groovy classes injected directly this is probably more complicated than the solution should be. It easier to specifically request services from the Injector.

This is how I have done this with Guice in the past.

Setting up Guice

Guice can do a lot of stuff around injecting servlets but the easiest way to get going is to simply store an Injector instance in the Servlet Context and then access that directly in the Groovlet.

This is done with a simple ServletContextListener that stores the Injector by its classname in the Servlet Context.

event.getServletContext().setAttribute(Injector.class.getName(), Guice.createInjector(new MyModule()));

Accessing the Injector

Once the injector is in context it is simple to extract (as context is already bound in the Groovlet scope).

Here is an example that prints out the names of the members of a popular beat combo.

import com.google.inject.Injector
import bands.BandRepository

def injector = context.getAttribute(Injector.class.getName())
def bands = injector.getInstance(BandRepository.class);
def beatles = bands.getBand("The Beatles")

html.html() {
    head()
    body() {
        h1("${beatles.getName()}")

        ul() {
            beatles.getMembers().each { li(it.getName())}
        }     
    }
}

Highlights

Notice that the heading has an interpolated value using the regular Groovy syntax.

Also any iterable can be used with the each method to generate output that would normally be created by a for loop.