Wednesday, April 17, 2013

Rich ApplicationContext in Spring Scala

The latest milestone release (1.0.0.M2) of Spring Scala brings you many of the brand new exciting features. Unfortunately as Spring Scala is still in the early development phase, there is no reference documented dedicated to this library. The documentation will be published before the first stable release of Spring Scala. However as both I and Spring Scala forum have been pinged with the questions about the reference documentation for new Spring Scala features, I decided to write some blog posts describing new goodies delivered to the Spring Scala community. This is the very first of these, demonstrating the awesomeness of the rich BeanFactory and ApplicationContext.

Let's start with the org.springframework.scala.context.RichApplicationContext. The latter trait provides Scala-friendly versions of the methods from the plain old Spring ApplicationContext. In order to convert ApplicationContext into RichApplicationContext you can use implicit conversion defined in the ApplicationContextConversions.toRichApplicationContext object.
import ApplicationContextConversions._
...
val context : ApplicationContext = ...

val nissan = context.bean[Nissan]
val xtrail = context.bean[Nissan](name = "xtrail")

// Return Map[String,Car].
val allCars = context.beansOfType[Car] 

// Return Seq[String].
val namesOfCars = context.beanNamesForType[Car]
If you like even more syntactic sugar you can use RichListableBeanFactory.appy() notation to retrieve the bean from the context.
import ApplicationContextConversions._
...
val context : ApplicationContext = ...

// Syntactic sugar magic!
val nissan = context[Nissan] 

// Same magic by bean name.
val xtrail : Nissan = context("xtrail")  
Keep in mind that org.springframework.scala.context.function.FunctionalConfigApplicationContext extends RichApplicationContext out of the box, so you don't need to use ApplicationContextConversions implicit conversion while working with this type of context.
// We can comment out context's implicit conversions
// import ApplicationContextConversions._
...
val context = FunctionalConfigApplicationContext[CarConfig]
val nissan = context[Nissan]
How do you like new Spring Scala context API? What else would you like Scala-friendly ApplicationContext to have?

2 comments: