Pages

Wednesday, July 6, 2011

Scala Function as Spring Bean (Spring and Scala)

With Scala gaining popularity a lot of developers are now wondering how Scala can integrate with existing and popular JVM-based frameworks.
One of the questions I've been asked recently if Scala Functions could be used as Spring Beans in the typical Dependency Injection model provided by Spring Framework. In other words can I inject Scala function into a Spring configured Java bean? The answer is not only 'Yes' but it is actually very simple, since Scala itself is very nicely integrated with Java and Scala Function is just a class.

Let's say we have a Scala function called PrintFunction
class PrintFunction extends Function1[String, Unit]{
   def apply(in: String) = println("From Scala function: " + in)
}
It is worth pointing out that Scala defines a group of traits from scala.Function0 to scala.Function9, allowing you to define functions with 0 to 9 parameters so you can easily integrate them with other classes. In our case we are using Function1 since we only passing one parameter. However we can clearly see that there is a second type argument in our definition of PrintFunction (e.g., Function1[String, Unit]). That is the return value and in our case it is Unit which would be the equivalent of Java 'void'.

So, to bootstrap this function as a Spring Bean all we need is to define it as Spring Bean

<bean id="prinitScalaFunction" class="olegz.scala.spring.PrintFunction"/>

Now it is just another Spring Bean which could be injected into any other bean that has PrintFunction property (see below).
public class SimpleSpringBean {

    private PrintFunction function;

    public void setFunction(PrintFunction function) {
        this.function = function;
    }
        
    public void printMessage(String message) {
        function.apply(message);
    }
}
. . . and its configuration:

<bean class="olegz.scala.spring.SimpleSpringBean">
<property name="function" ref="prinitScalaFunction"/>
</bean>

Now all we need is start Spring Application Context and call printMessage(String) method of SimpleSpringBean. This method will invoke Function's apply(String) method, or we can simply get the function itself and call its apply(String) method.

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("scala-config.xml", SpringDemo.class);
    SimpleSpringBean bean = context.getBean(SimpleSpringBean.class);
    bean.printMessage("Hello Spring-Scala");
}
You should see the following output:
From Scala function: Hello Spring-Scala
For more details check out this sources here https://github.com/olegz/scala-spring-samples/tree/master/src/test/scala/olegz/scala/spring

1 comment: