Chapter 24. Dynamic language support

24.1. Introduction

Spring 2.0 introduces comprehensive support for using classes and objects that have been defined using a dynamic language (such as JRuby) with Spring.

This support allows you to write any number of classes in a supported dynamic language, and have the Spring container transparently instantiate, configure and dependency inject the resulting objects.

The dynamic languages currently supported are:

  • JRuby

  • Groovy

  • BeanShell

Fully working examples of where this dynamic language support can be immediately useful are described in the section entitled Section 24.4, “Scenarios”.

Please note that the dynamic language support detailed in this chapter is only available in Spring versions 2.0 and above. Currently there are no plans to backport the dynamic language support to previous versions of Spring (most notably the 1.2.x line).

24.2. A first example

This bulk of this chapter is concerned with describing the dynamic language support in detail. Before diving into all of the ins and outs of the dynamic language support, let's look at a quick example of a bean defined in a dynamic language.

The dynamic language for this first bean is Groovy (the basis of this example was taken from the Spring test suite, so if you want to see equivalent examples in any of the other supported languages, take a look in the source code).

Let's look at the Messenger interface that the Groovy bean is going to be implementing. Note that this interface is defined in plain Java. Dependent objects that are injected with a reference to the Messenger won't know that the underlying implementation is a Groovy script.

package org.springframework.scripting;

public interface Messenger {

    String getMessage();
}

Here is the definition of a class that has a dependency on the Messenger interface.

package org.springframework.scripting;

public class DefaultBookingService implements BookingService {

    private Messenger messenger;

    public void setMessenger(Messenger messenger) {
        this.messenger = messenger;
    }

    public void processBooking() {
        // use the injected Messenger object...
    }
}

Here is an implementation of the Messenger interface in Groovy.

// from the file 'Messenger.groovy'
package org.springframework.scripting.groovy;

// import the Messenger interface (written in Java) that is to be implemented
import org.springframework.scripting.Messenger

// define the implementation in Groovy
class GroovyMessenger implements Messenger {

    @Property String message;
}

Finally, here are the bean definitions that will effect the injection of the Groovy-defined Messenger implementation into an instance of the DefaultBookingService class.

[Note]Note

To use the custom dynamic language tags to define dynamic-language-backed beans, you need to have the XML Schema preamble at the top of your Spring XML configuration file. You also need to be using a Spring ApplicationContext implementations as your IoC container. Using the dynamic-language-backed beans with a plain BeanFactory implementation is supported, but you have to manage the plumbing of the Spring internals to do so.

For more information on schema-based configuration, see Appendix A, XML Schema-based configuration.

<?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">

    <!-- this is the bean definition for the Groovy-backed Messenger implementation -->
    <lang:groovy id="messenger" script-source="classpath:Messenger.groovy">
        <lang:property name="message" value="I Can Do The Frug" />
    </lang:groovy>

    <!-- an otherwise normal bean that will be injected by the Groovy-backed Messenger -->
    <bean id="bookingService" class="x.y.DefaultBookingService">
        <property name="messenger" ref="messenger" />
    </bean>

</beans>

The bookingService bean (a DefaultBookingService) can now use its private messenger member variable as normal because the Messenger instance that was injected into it is a Messenger instance. There is nothing special going on here, just plain Java and plain Groovy.

Hopefully the above XML snippet is self-explanatory, but don't worry unduly if it isn't. Keep reading for the in-depth detail on the whys and wherefores of the above configuration.

24.3. Defining beans that are backed by dynamic languages

This section describes exactly how you define Spring managed beans in any of the supported dynamic languages.

Please note that this chapter does not attempt to explain the syntax and idioms of the supported dynamic languages. For example, if you want to use Groovy to write certain of the classes in your application, then the assumption is that you already know Groovy. If you need further details about the dynamic languages themselves, please consult the section entitled Section 24.5, “Further Resources” at the end of this chapter.

24.3.1. Common concepts

The steps involved in using dynamic-language-backed beans are as follows:

  1. Write the test for the dynamic language source code (naturally)

  2. Then write the dynamic language source code itself :)

  3. Define your dynamic-language-backed beans using the appropriate <lang:language/> element in the XML configuration (you can of course define such beans programmatically using the Spring API - although you will have to consult the source code for directions on how to do this as this type of advanced configuration is not covered in this chapter). Note this is an iterative step. You will need at least one bean definition per dynamic language source file (although the same dynamic language source file can of course be referenced by multiple bean definitions).

The first two steps (testing and writing your dynamic language source files) are beyond the scope of this chapter. Refer to the language specification and / or reference manual for your chosen dynamic language and crack on with developing your dynamic language source files. You will first want to read the rest of this chapter though, as Spring's dynamic language support does make some (small) assumptions about the contents of your dynamic language source files.

24.3.1.1. The <lang:language/> element

The final step involves defining dynamic-language-backed bean definitions, one for each bean that you want to configure (this is no different to normal Java bean configuration). However, instead of specifying the fully qualified classname of the class that is to be instantiated and configured by the container, you use the <lang:language/> element to define the dynamic language-backed bean.

Each of the supported languages has a corresponding <lang:language/> element:

  • <lang:jruby/> (JRuby)

  • <lang:groovy/> (Groovy)

  • <lang:bsh/> (BeanShell)

The exact attributes and child elements that are available for configuration depends on exactly which language the bean has been defined in (the language-specific sections below provide the full lowdown on this).

24.3.1.2. Refreshable beans

One of the (if not the) most compelling value adds of the dynamic language support in Spring is the 'refreshable bean' feature.

A refreshable bean is a dynamic-language-backed bean that with a small amount of configuration, a dynamic-language-backed bean can monitor changes in its underlying source file resource, and then reload itself when the dynamic language source file is changed (for example when a developer edits and saves changes to the file on the filesystem).

This allows a developer to deploy any number of dynamic language source files as part of an application, configure the Spring container to create beans backed by dynamic language source files (using the mechanisms described in this chapter), and then later, as requirements change or some other external factor comes into play, simply edit a dynamic language source file and have any change they make reflected in the bean that is backed by the changed dynamic language source file. There is no need to shut down a running application (or redeploy in the case of a web application). The dynamic-language-backed bean so amended will pick up the new state and logic from the changed dynamic language source file.

[Note]Note

Please note that this feature is off by default.

Let's take a look at an example to see just how easy it is to start using refreshable beans. To turn on the refreshable beans feature, you simply have to specify exactly one additional attribute on the <lang:language/> element of your bean definition. So if we stick with the example from earlier in this chapter, here's what we would change in the Spring XML configuration to effect refreshable beans:

<beans>

    <!-- this bean is now 'refreshable' due to the presence of the 'refresh-check-delay' attribute -->
    <lang:groovy id="messenger"
          refresh-check-delay="5000" <!-- switches refreshing on with 5 seconds between checks -->
          script-source="classpath:Messenger.groovy">
        <lang:property name="message" value="I Can Do The Frug" />
    </lang:groovy>

    <bean id="bookingService" class="x.y.DefaultBookingService">
        <property name="messenger" ref="messenger" />
    </bean>

</beans>

That really is all you have to do. The 'refresh-check-delay' attribute defined on the 'messenger' bean definition is the number of milliseconds after which the bean will be refreshed with any changes made to the underlying dynamic language source file. You can turn off the refresh behavior by assigning a negative value to the 'refresh-check-delay' attribute. Remember that, by default, the refresh behavior is disabled. If you don't want the refresh behavior, then simply don't define the attribute.

If we then run the following application we can exercise the refreshable feature; please do excuse the 'jumping-through-hoops-to-pause-the-execution' shenanigans in this next slice of code. The System.in.read() call is only there so that the execution of the program pauses while I (the author) go off and edit the underlying dynamic language source file so that the refresh will trigger on the dynamic-language-backed bean when the program resumes execution.

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

public final class Boot {

    public static void main(final String[] args) throws Exception {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        Messenger messenger = (Messenger) ctx.getBean("messenger");
        System.out.println(messenger.getMessage());
        // pause execution while I go off and make changes to the source file...
        System.in.read();
        System.out.println(messenger.getMessage());
    }
}

Let's assume then, for the purposes of this example, that all calls to the getMessage() method of Messenger implementations have to be changed such that the message is surrounded by quotes. Below are the changes that I (the author) make to the Messenger.groovy source file when the execution of the program is paused.

package org.springframework.scripting

class GroovyMessenger implements Messenger {

    private String message = "Bingo"

    public String getMessage() {
        // change the implementation to surround the message in quotes
        return "'" + this.message + "'"
    }

    public void setMessage(String message) {
        this.message = message
    }
}

When the program executes, the output before the input pause will be I Can Do The Frug. After the change to the source file is made and saved, and the program resumes execution, the result of calling the getMessage() method on the dynamic-language-backed Messenger implementation will be 'I Can Do The Frug' (notice the inclusion of the additional quotes).

It is important to understand that changes to a script will not trigger a refresh if said changes occur within the window of the 'refresh-check-delay' value. It is equally important to understand that changes to the script are not actually 'picked up' until a method is called on the dynamic-language-backed bean. It is only when a method is called on a dynamic-language-backed bean that it checks to see if its underlying script source has changed. Any exceptions relating to refreshing the script (such as encountering a compilation error, or finding that the script file has been deleted) will result in a fatal exception being propagated to the calling code.

The refreshable bean behavior described above does not apply to dynamic language source files defined using the <lang:inline-script/> element notation (see the section entitled Section 24.3.1.3, “Inline dynamic language source files”). Additionally, it only applies to beans where changes to the underlying source file can actually be detected; for example, by code that checks the last modified date of a dynamic language source file that exists on the filesystem.

24.3.1.3. Inline dynamic language source files

The dynamic language support can also cater for dynamic language source files that are embedded directly in Spring bean definitions. More specifically, the <lang:inline-script/> element allows you to define dynamic language source immediately inside a Spring configuration file. An example will perhaps make the inline script feature crystal clear:

<lang:groovy id="messenger">
    <lang:property name="message" value="I Can Do The Frug" />
    <lang:inline-script>
package org.springframework.scripting.groovy;

import org.springframework.scripting.Messenger

class GroovyMessenger implements Messenger {

    @Property String message;
}
    </lang:inline-script>
</lang:groovy>

If we put to one side the issues surrounding whether it is good practice to define dynamic language source inside a Spring configuration file, the <lang:inline-script/> element can be useful in some scenarios. For instance, we might want to quickly add a Spring Validator implementation to a Spring MVC Controller. This is but a moment's work using inline source. (See the section entitled Section 24.4.2, “Scripted Validators” for such an example.)

Also, don't forget that in the case of more complex classes than the one shown above, you may have to surround the inline source in a <![CDATA[]]> region (see below for an example).

Below is an example of defining the source for a JRuby-based bean directly in a Spring XML configuration file using the inline: notation. (Notice the use of the &lt; characters to denote a '<' character.)

<lang:jruby id="messenger" script-interfaces="org.springframework.scripting.Messenger">
    <lang:inline-script>
require 'java'

include_class 'org.springframework.scripting.Messenger'

class RubyMessenger &lt; Messenger

 def setMessage(message)
  @@message = message
 end

 def getMessage
  @@message
 end
 
end
    </lang:inline-script>
    <lang:property name="message" value="Hello World!" />
</lang:jruby>

24.3.1.4. Understanding Constructor Injection in the context of dynamic-language-backed beans

There is one very important thing to be aware of with regard to Spring's dynamic language support. Namely, it is not (currently) possible to supply constructor arguments to dynamic-language-backed beans (and hence constructor-injection is not available for dynamic-language-backed beans).

In the interests of making this special handling of constructors and properties 100% clear, the following mixture of code and configuration will not work.

Here is an implementation of the Messenger interface in Groovy.

// from the file 'Messenger.groovy'
package org.springframework.scripting.groovy;

import org.springframework.scripting.Messenger

class GroovyMessenger implements Messenger {

    GroovyMessenger() {}

    // this constructor is not available for Constructor Injection...
    GroovyMessenger(String message) {
        this.message = message;
    }

    @Property String message;

    @Property String anotherMessage
}
<lang:groovy id="badMessenger"
    script-source="classpath:Messenger.groovy">

    <!-- this next constructor argument will *not* be injected into the GroovyMessenger -->
    <!--     in fact, this isn't even allowed according to the schema -->
    <constructor-arg value="This will *not* work" />
    
    <!-- only property values are injected into the dynamic-language-backed object -->
    <lang:property name="anotherMessage" value="Passed straight through to the dynamic-language-backed object" />

</lang>

In practice this limitation is not as significant as it first appears since setter injection is the injection style favored by the overwhelming majority of developers anyway (let's leave the discussion as to whether that is a good thing to another day).

24.3.2. JRuby beans

From the JRuby homepage...

[JRuby is an] Effort to recreate the Ruby interpreter written in Java, and a Ruby to Java bytecode compiler.

In keeping with the Spring philosophy of offering choice, Spring's dynamic language support also supports beans defined in the JRuby language. The JRuby language is (of course) based on the quite intuitive Ruby language, and has support for inline regular expressions, blocks (closures), and a whole host of other features that do make solutions for some domain problems a whole lot easier to develop.

The implementation of the JRuby dynamic language support in Spring is interesting in that what happens is this: Spring creates a JDK dynamic proxy implementing all of the interfaces that are specified in the 'script-interfaces' attribute value of the <lang:ruby> element (this is why you must supply at least one interface in the value of said attribute, and (accordingly) program to interfaces when using JRuby-backed beans).

Let's look at a fully working example of using a JRuby-based bean. Here is the JRuby implementation of the Messenger interface that was defined earlier in this chapter (for your convenience it is repeated below).

package org.springframework.scripting;

public interface Messenger {

    String getMessage();

}
require 'java'

include_class 'org.springframework.scripting.Messenger'

class RubyMessenger < Messenger

 def setMessage(message)
  @@message = message
 end

 def getMessage
  @@message
 end

end

RubyMessenger.new # this last line is not essential (but see below)

And here is the Spring XML that defines an instance of the RubyMessenger JRuby bean.

<lang:jruby id="messageService"
            script-interfaces="org.springframework.scripting.Messenger"
            script-source="classpath:RubyMessenger.rb">
    
    <lang:property name="message" value="Hello World!" />

</lang:jruby>

Take note of the last line of that JRuby source ('RubyMessenger.new'). When using JRuby in the context of Spring's dynamic language support, you are encouraged to instantiate and return a new instance of the JRuby class that you want to use as a dynamic-language-backed bean as the result of the execution of your JRuby source. You can achieve this by simply instantiating a new instance of your JRuby class on the last line of the source file like so:

require 'java'

include_class 'org.springframework.scripting.Messenger'

# class definition same as above...

# instantiate and return a new instance of the RubyMessenger class
RubyMessenger.new

If you forget to do this, it's not the end of the world; this will however result in Spring having to trawl (reflectively) through the type representation of your JRuby class looking for a class to instantiate. In the grand scheme of things this will be so fast that you'll never notice it, but it is something that can be avoided by simply having a line such as the one above as the last line of your JRuby script. If you don't supply such a line, or if Spring cannot find a JRuby class in your script to instantiate then an opaque ScriptCompilationException will be thrown immediately after the source is executed by the JRuby interpreter. The key text that identifies this as the root cause of an exception can be found immediately below (so if your Spring container throws the following exception when creating your dynamic-language-backed bean and the following text is there in the corresponding stacktrace, this will hopefully allow you to identify and then easily rectify the issue):

org.springframework.scripting.ScriptCompilationException: Compilation of JRuby script returned ''

To rectify this, simply instantiate a new instance of whichever class you want to expose as a JRuby-dynamic-language-backed bean (as shown above). Please also note that you can actually define as many classes and objects as you want in your JRuby script; what is important is that the source file as a whole must return an object (for Spring to configure).

See the section entitled Section 24.4, “Scenarios” for some scenarios where you might want to use JRuby-based beans.

24.3.3. Groovy beans

From the Groovy homepage...

Groovy is an agile dynamic language for the Java 2 Platform that has many of the features that people like so much in languages like Python, Ruby and Smalltalk, making them available to Java developers using a Java-like syntax.

If you have read this chapter straight from the top, you will already have seen an example of a Groovy-dynamic-language-backed bean. Let's look at another example (again using an example from the Spring test suite).

[Note]Note

Groovy itself requires JDK 1.4+.

package org.springframework.scripting;

public interface Calculator {

    int add(int x, int y);
}

Here is an implementation of the Calculator interface in Groovy.

// from the file 'calculator.groovy'
package org.springframework.scripting.groovy

class GroovyCalculator implements Calculator {

    int add(int x, int y) {
        x + y
    }
}

And here is the attendant Spring configuration (XML).

<-- from the file 'beans.xml' -->
<beans>
    <lang:groovy id="calculator" script-source="classpath:calculator.groovy"/>
</beans>

Lastly, here is a small application to exercise the above configuration.

package org.springframework.scripting;

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

public class Main {

    public static void Main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        Calculator calc = (Calculator) ctx.getBean("calculator");
        System.out.println(calc.add(2, 8));
    }
}

The resulting output from running the above program will be (unsurprisingly) 10. (Exciting example, huh? Remember that the intent is to illustrate the concept. Please consult the dynamic language showcase project for a more complex example, or indeed the section entitled Section 24.4, “Scenarios” later in this chapter).

It is important that you do not define more than one class per Groovy source file. While this is perfectly legal in Groovy, it is (arguably) a bad practice: in the interests of a consistent approach, you should (in the opinion of this author) respect the standard Java conventions of one (public) class per source file.

That is pretty much it so far as Groovy-based beans go. Groove on!

24.3.4. BeanShell beans

From the BeanShell homepage...

BeanShell is a small, free, embeddable Java source interpreter with dynamic language features, written in Java. BeanShell dynamically executes standard Java syntax and extends it with common scripting conveniences such as loose types, commands, and method closures like those in Perl and JavaScript.

In contrast to Groovy, BeanShell-backed bean definitions require some (small) additional configuration. The implementation of the BeanShell dynamic language support in Spring is interesting in that what happens is this: Spring creates a JDK dynamic proxy implementing all of the interfaces that are specified in the 'script-interfaces' attribute value of the <lang:bsh> element (this is why you must supply at least one interface in the value of said attribute, and (accordingly) program to interfaces when using BeanShell-backed beans). This means that every method call on a BeanShell-backed object is going through the JDK dynamic proxy invocation mechanism.

Let's look at a fully working example of using a BeanShell-based bean that implements the Messenger interface that was defined earlier in this chapter (repeated below for your convenience).

package org.springframework.scripting;

public interface Messenger {

    String getMessage();
}

Here is the BeanShell 'implementation' (the term is used loosely here) of the Messenger interface.

String message;

String getMessage() {
    return message;
}

void setMessage(String aMessage) {
    message = aMessage;
}

And here is the Spring XML that defines an 'instance' of the above 'class' (again, the term is used very loosely here).

<lang:bsh id="messageService" script-source="classpath:BshMessenger.bsh"
    script-interfaces="org.springframework.scripting.Messenger">

    <lang:property name="message" value="Hello World!" />
</lang:bsh>

See the section entitled Section 24.4, “Scenarios” for some scenarios where you might want to use BeanShell-based beans.

24.4. Scenarios

The possible scenarios where defining Spring managed beans in a scripting language would be beneficial are, of course, many and varied. This section describes two possible use cases for the dynamic language support in Spring.

Please also note that the Spring distribution ships with a showcase project for this dynamic language support in the relevant section of the Spring distribution. (A showcase project is a small project that is limited in scope to covering one particular aspect of the Spring Framework.)

24.4.1. Scripted Spring MVC Controllers

One group of classes that may benefit from using dynamic-language-backed beans is that of Spring MVC controllers. In pure Spring MVC applications, the navigational flow through a web application is to a large extent determined by code encapsulated within your Spring MVC controllers. As the navigational flow and other presentation layer logic of a web application needs to be updated to respond to support issues or changing business requirements, it may well be easier to effect any such required changes by editing one or more dynamic language source files and seeing those changes being immediately reflected in the state of a running application.

Remember that in the lightweight architectural model espoused by projects such as Spring, you are typically aiming to have a really thin presentation layer, with all the meaty business logic of an application being contained in the domain and service layer classes. Developing Spring MVC controllers as dynamic-language-backed beans allows you to change presentation layer logic by simply editing and saving text files; any changes to such dynamic language source files will (depending on the configuration) automatically be reflected in the beans that are backed by said dynamic language source files.

[Note]Note

Please note that in order to effect this automatic 'pickup' of any changes to dynamic-language-backed beans, you will have had to enable the 'refreshable beans' functionality. See the section entitle Section 24.3.1.2, “Refreshable beans” for a full treatment of this feature.

Find below an example of an org.springframework.web.servlet.mvc.Controller implemented using the Groovy dynamic language. This example is taken in part from the dynamic language support showcase project that is supplied with the Spring distribution; please do see the project in the 'samples/showcases/dynamvc/' directory of the Spring distribution.

<!-- from the file '/WEB-INF/groovy/FortuneController.groovy' -->
package org.springframework.showcase.fortune.web;

import org.springframework.showcase.fortune.service.FortuneService;
import org.springframework.showcase.fortune.domain.Fortune;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FortuneController implements Controller {

    @Property FortuneService fortuneService

    public ModelAndView handleRequest(
            HttpServletRequest request, HttpServletResponse httpServletResponse) {

        return new ModelAndView("tell", "fortune", this.fortuneService.tellFortune())
    }

}

The attendant bean definition for the above Controller might look like this:

<lang:groovy id="fortune"
             refresh-check-delay="3000"
             script-source="/WEB-INF/groovy/FortuneController.groovy">
    <lang:property name="fortuneService" ref="fortuneService"/>
</lang:groovy>

24.4.2. Scripted Validators

Another area of application development with Spring that may benefit from the flexibility afforded by dynamic-language-backed beans is that of validation. It may be easier to express complex validation logic using a loosely typed dynamic language (that may also have support for inline regular expressions) as opposed to regular Java.

Again, developing validators as dynamic-language-backed beans allows you to change validation logic by simply editing and saving a simple text file; any such changes will (depending on the configuration) automatically be reflected in the execution of a running application and would not require the restart of an application.

[Note]Note

Please note that in order to effect the automatic 'pickup' of any changes to dynamic-language-backed beans, you will have had to enable the 'refreshable beans' feature. See the section entitled Section 24.3.1.2, “Refreshable beans” for a full and detailed treatment of this feature.

Find below an example of a Spring org.springframework.validation.Validator implemented using the Groovy dynamic language. (See the section entitled Section 5.2, “Validation using Spring's Validator interface” for a discussion of the Validator interface.)

import org.springframework.validation.Validator
import org.springframework.validation.Errors
import org.springframework.beans.TestBean

public class TestBeanValidator implements Validator {

    boolean supports(Class clazz) {
        return TestBean.isAssignableFrom(clazz)
    }
    
    void validate(Object bean, Errors errors) {
        String name = bean.getName()
        if(name == null || name.trim().length == 0) {
            errors.reject("whitespace", "Cannot be composed wholly of whitespace")
        }
    }
}

24.5. Further Resources

Find below links to further resources about the various dynamic languages described in this chapter.

Some of the more active members of the Spring community have also added support for a number of additional dynamic languages above and beyond the ones covered in this chapter. While it is possible that such third party contributions may be added to the list of languages supported by the main Spring distribution, your best bet for seeing if your favourite scripting language is supported is the Spring Modules project.