Wednesday, May 2, 2007

Groovy is enterprise ready

It has been a long time since my last post. But important things are happening for enterprise scripting. Yes, Groovy-1.1-beta-1 was released yesterday. This release has new features that could speed up its adoption at the enterprise level. In this post, let's focus on annotations that is something brought by Java 5. Nowadays, annotations are everywhere from Spring Framework, Hibernate, TestNG to the newcomer Google-Guice lightweight dependency injection framework.
Let's see how Guice and Groovy can be used jointly.
All you need is a fresh Groovy 1.1-beta-1 install and guice-1.0.jar and aopalliance-1.0.jar from Google-Guice. As an example, I will use the stupid mathematic application I am using for the GroovySOAP tutorial.
Let say, you have an addition contract like this one:

import com.google.inject.*
interface Calculator {
def add(a,b)
}

Here is an obvious instanciation of that contract (this should be implemented as a singleton):

@Singleton
class CalculatorImpl implements Calculator {
def add(a, b) {a + b }
}

The next step is to write the client that will need that service to be injected. In Groovy, this is as simple as shown below. The @Inject annotation is used for that purpose.

class Client {
@Inject
Calculator calc

def executeCalc(a, b) { calc.add(a,b) }
}

What is not yet done is the wiring between our client and the implementation class. This can be done programmatically using the so called Modules in Guice. Here is what I am doing here:

class MyModule implements Module {
void configure(Binder binder) {
binder.bind(Calculator).to(CalculatorImpl)
}
}

At this point, we are done. Here is how you can use your client in Groovy:

def injector = Guice.createInjector(new MyModule())
def client = injector.getInstance(Client)
assert 3 == client.executeCalc(1,2)

If you want to learn more on this topic, here are further reading on Guicy by MrG and some early experiment on JPA and annotations in Groovy by Romain.

No comments: