Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

Background

The Spring Framework is a leading full-stack Java/J2EE application framework. It is aimed primarily at Java projects and delivers significant benefits such as reducing development effort and costs while providing facilities to improve test coverage and quality. It also has mechanisms for allowing beans to be backed by dynamic language code including Groovy and other languages.

Let's have a look at how to use Spring's support for writing dynamic language backed beans to extend an existing Java application. The existing Java application prints out information about countries in sorted order. We want to be able to add new countries and new sorting algorithms but using different languages for each one. Our goal is to not have to change the original Java code but add the new features just through the application wiring.

The Existing Application (Spring and Java)

Suppose we have the following interface:

Code Block
java
java
package spring;

public interface Country {
    long getPopulation();
    String getCapital();
}

And the following implementation class:

Code Block
java
java
package spring;

public class USA implements Country {
    private final String capital;
    private final long population;

    public USA(String capital, long population) {
        this.population = population;
        this.capital = capital;
    }

    public String toString() {
        return "USA[Capital=" + capital + ", Population=" + population + "]";
    }

    public long getPopulation() {
        return population;
    }

    public String getCapital() {
        return capital;
    }
}

Spring supports the Dependency Injection style of coding. This style encourages classes which depend on classes like USA not to hard-code that dependency, e.g. no fragments of code like 'new USA(...)' and no 'import ...USA;'. Such a style allows us to change the concrete implementations we depend on for testing purposes or at a future point in time as our program evolves. In our example above, we might declaratively state our dependencies in a beans.xml file as follows:

Code Block
xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
  <bean id="usa" class="spring.USA">
    <constructor-arg value="Washington, D.C."/>
    <constructor-arg value="298444215"/>
  </bean>
</beans>

In this example, the <constructor-arg/> element allows us to use constructor-based injection.

Having done this, we can get access to our beans through a variety of mechanisms. Normally, access to the beans is mostly transparent. In our case though, we are going to make access explicit so you can see what is going on. Our main method might look like this:

Code Block
java
java
package spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Arrays;

public class SortMain {
    public static void main(String[] args) {
        try {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
            Country usa = (Country) ctx.getBean("usa");
            System.out.println("USA Info:\n" + usa);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Running this results in:

Code Block
none
none
USA Info:
USA[Capital=Washington, D.C., Population=298444215]

Spring and Groovy

We can extend this example and introduce Groovy in a number of ways. Firstly, we can create the following Groovy class:

Code Block
package spring
public class Australia implements Country {
    String capital
    long population
    String toString() {
        return "Australia[Capital=" + capital + ", Population=" + population + "]"
    }
}

And this one too:

Code Block
package spring
public class NewZealand extends Australia implements Country {
    String toString() {
        return "NewZealand[Capital=" + capital + ", Population=" + population + "]"
    }
}

So long as the corresponding .class file is available on the classpath (e.g. by your IDE or by manually running groovyc), we can simply reference this class in our beans.xml file. E.g. for the first class we can use:

Code Block
...
<bean id="country1" class="spring.Australia">
    <property name="capital" value="Canberra"/>
    <property name="population" value="20264082"/>
</bean>
...

Alternatively, if the source file is on the classpath, we can use special Spring notation to reference it, e.g. for the second class we can use:

Code Block
...
<lang:groovy id="country3" script-source="classpath:spring/NewZealand.groovy">
    <lang:property name="capital" value="Wellington" />
    <lang:property name="population" value="4076140" />
</lang:groovy>
...

In these examples, the <property/> and <lang:property/> elements allows us to use setter-based injection.

Spring and JRuby

If we prefer to code in another language (with a few restrictions - see below), Spring supports other languages too, e.g.:

Code Block
require 'java'

include_class 'spring.Country'

class Fiji < Country
    def getCapital()
        @capital
    end
    def getPopulation()
        @population
    end
    def setCapital(capital)
        @capital = capital
    end
    def setPopulation(population)
        @population = population
    end
    def to_s()
        "Fiji[Capital=" + @capital + ", Population=" + getPopulation().to_s() + "]"
    end
end
Fiji.new()
Code Block
xml
xml
...
<lang:jruby id="country4" script-interfaces="spring.Country" script-source="classpath:spring/Fiji.rb">
    <lang:property name="capital" value="Suva" />
    <lang:property name="population" value="905949" />
</lang:jruby>
...

Spring and Groovy Again

But wait there's more ...

Suppose now that we wish to sort our countries according to population size. We don't want to use Java's built-in sort mechanisms as some of them rely on our objects implementing the Comparable interface and we don't want that noise in our Ruby script. Instead we will use Groovy. We could simply write a Sort class in Groovy and reference as we have done above. This time however we are going to use an additional Spring feature and have the scripting code within our beans.xml file. First we define the following Java interface:

Code Block
java
java
package spring;

import java.util.List;

public interface Sorter {
    List sort(Country[] unsorted);
}

We can then include the Groovy sort code directly into the beans.xml file as follows:

Code Block
xml
xml
...
<lang:groovy id="sorter">
<lang:inline-script><![CDATA[
    package spring
    class CountrySorter implements Sorter {
        String order
        List sort(Country[] items) {
            List result = items.toList().sort{ p1, p2 -> p1.population <=> p2.population }
            if (order == "reverse") return result.reverse() else return result
        }
    }
]]></lang:inline-script>
    <lang:property name="order" value="forward" />
</lang:groovy>
...

Putting it all together

We now combine all of the approaches above in a final example.

Here is the complete beans.xml file:

Code Block
xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<bean id="country1" class="spring.Australia">
    <property name="capital" value="Canberra"/>
    <property name="population" value="20264082"/>
</bean>
<bean id="country2" class="spring.USA">
    <constructor-arg value="Washington, D.C."/>
    <constructor-arg value="298444215"/>
</bean>
<lang:groovy id="country3" script-source="classpath:spring/NewZealand.groovy">
    <lang:property name="capital" value="Wellington" />
    <lang:property name="population" value="4076140" />
</lang:groovy>
<lang:jruby id="country4" script-interfaces="spring.Country" script-source="classpath:spring/Fiji.rb">
    <lang:property name="capital" value="Suva" />
    <lang:property name="population" value="905949" />
</lang:jruby>
<lang:groovy id="sorter">
<lang:inline-script><![CDATA[
    package spring
    class CountrySorter implements Sorter {
        String order
        List sort(Country[] items) {
            List result = items.toList().sort{ p1, p2 -> p1.population <=> p2.population }
            if (order == "reverse") return result.reverse() else return result
        }
    }
]]></lang:inline-script>
    <lang:property name="order" value="forward" />
</lang:groovy>
</beans>

Our Java code to use this example looks like:

Code Block
java
java
package spring;

import java.util.Arrays;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SortMain {
    public static void main(String[] args) {
        try {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
            Country[] countries = {
                (Country) ctx.getBean("country1"), (Country) ctx.getBean("country2"),
                (Country) ctx.getBean("country3"), (Country) ctx.getBean("country4")
            };
            Sorter sorter = (Sorter) ctx.getBean("sorter");
            System.out.println("Unsorted:\n" + Arrays.asList(countries));
            System.out.println("Sorted:\n" + sorter.sort(countries));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And the resulting output (with a little bit of hand formatting) looks like:

Code Block
none
none
Unsorted:
[Australia[Capital=Canberra, Population=20264082],
 USA[Capital=Washington, D.C., Population=298444215],
 NewZealand[Capital=Wellington, Population=4076140],
 JRuby object [Fiji[Capital=Suva, Population=905949]]]

Sorted:
[JRuby object [Fiji[Capital=Suva, Population=905949]],
 NewZealand[Capital=Wellington, Population=4076140],
 Australia[Capital=Canberra, Population=20264082],
 USA[Capital=Washington, D.C., Population=298444215]]

What we didn't tell you yet

  • Spring supports BeanShell in addition to JRuby and Groovy
  • Spring supports the concept of refreshable beans when using the <lang:language/> element so that if your bean source code changes, the bean will be reloaded (see GINA or the Spring doco for more details)
  • The Groovy scripting examples in the current Spring documentation are based on an old version of Groovy, ignore the @Property keywords and use the latest groovy-all-xxx.jar instead of the jars they recommend
  • The <lang:language/> element currently only supports setter-based injection
  • Spring automatically converts between the object models of the various languages but there are some limitations (particularly with JRuby - see the next section)

Current Limitations

Currently using the Groovy language through Spring is extensively supported. Using other languages like JRuby takes a little more care. Try restricting your JRuby methods to ones which take and return simple data types, e.g. long and String. You may also find that certain operations don't work as you'd expect when working between Ruby and other languages, e.g. if you defined a compareTo method in our Fiji.rb file, it would return long by default rather than the int which Java is expecting. In addition, the compareTo method takes an other object as a parameter. Currently the wrapping of this other object from Java or Groovy into a Ruby object hides the original Java methods.

Further Information