Tuesday, August 16, 2005

Use Groovy with Spring

Groovy is an interesting script engine on the JVM. The main is to provide an embedded component of a Java/J2EE application, to help write and customize business rules, or other moving parts of your application [cf G. Laforge].

I. Support in Spring

Spring offers a support for script tools in the sandbox. This support provides a generic component that can be extended in order to plug an implementation for a dedicated tool. This framework is localized in the org.springframework.beans.factory.script package and the groovy support in the org.springframework.beans.factory.script.groovy package.
This support is based on the facility of Spring to configure beans based on factory. Thus, the configuration of a Groovy object is divided into two steps:

  • Configuration of the Spring factory for Groovy

  • Configuration of the bean representing a Groovy object


  • The factory is simply configured as following:


    <bean id="groovyScriptFactory"
    class="org.springframework.beans.factory.script.groovy.GroovyScriptFactory">
    <property name="expirySeconds">
    <value>1</value>
    </property>
    </bean>


    Then you can configure your script with its location and inject all the properties used by it:


    <bean id="testGroovy" singleton="true"
    factory-bean="groovyScriptFactory"
    factory-method="create">
    <constructor-arg>
    <value>classpath:/groovy/simple.groovy</value>
    </constructor-arg>
    <property name="message">
    <value>the value of my propertylt;/value>
    </property>
    </bean>


    The Groovy script used will be the following. You can see that the value of the "message" property has been injected using Spring...


    package groovy;

    public class TestImpl implements Test {
    @Property test;
    @Property message;
    @Property method;
    @Property list = {
    param ->
    println "list - param : ${param} - "+param;
    };

    @Property Closure list1 = {
    param ->
    println "hoho! list1 - param : ${param} - "+param;
    };

    public TestImpl() {
    method = { |name| println "Hello, ${name}" }
    }

    void test() {
    println message;
    method(message);
    list("test");
    }
    }


    In our case, we expose the bean on Groovy thanks to the Test interface, so the application see it and doesn't know that the implementation is a Groovy script!

    However, this use isn't mandatory and you can see the Groovy script as a GroovyObject directly and nevertheless inject properties with Spring!!

    In the next part of "Use Groovy with Spring", we will show and explain how Steven Devijver load and construct a J2EE based on Groovy scripts and its closure feature, in the Grails project.

    No comments: