Pages

Wednesday, July 6, 2011

Implementing Spring's FactoryBean in Scala

Spring Framework provides many different extension points. One of them is FactoryBean
The details about FactoryBeans are described here. All I'll show is how to implement one in Scala, by extending on the previous post Scala Function as Spring Bean (Spring and Scala)
Let's say creating an instance of the Scala function requires some logic that could not or should not be handled by a simple constructor invocation. This would be a perfect case for a FactoryBean and we can easily implement one in Scala

So to create our PrintFunction via FactoryBean we can implement one in Java or in Scala. Below is the Scala implementation of Spring's FactoryBean which creates and instance of PrintFunction while also printing a message stating that it is creating a PrintFunction.
class ScalaFactoryBean extends FactoryBean[PrintFunction] {
  
  val myFunction = new PrintFunction()

  def getObject(): PrintFunction = {  
    println("Creating 'PrintFunction'")
 return myFunction
  }

  def getObjectType(): Class[PrintFunction] = { 
    classOf[PrintFunction]
  }

  def isSingleton(): Boolean = { 
    true 
  }
}
. . .and its configuration:

<bean id="prinitScalaFunctionFB" class="olegz.scala.spring.ScalaFactoryBean"/>
<bean id="functionViaFactoryBean" class="olegz.scala.spring.SimpleSpringBean">
     <property name="function" ref="prinitScalaFunctionFB"/>
</bean>

From this point on it is pure Spring
public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("scala-config.xml", SpringDemo.class);
  
    SimpleSpringBean functionViaFactoryBean = context.getBean("functionViaFactoryBean", SimpleSpringBean.class);
    functionViaFactoryBean.printMessage("Hello Spring-Scala");
}

For more info check out the source code here: https://github.com/olegz/scala-spring-samples/tree/master/src/test/scala/olegz/scala/spring

No comments: