Monday, April 22, 2013

Building functional application context with Spring Scala

The is the second post of mine presenting the latest changes to the bleeding-edge Spring Scala 1.0.0.M2 release of the Spring Scala project from the Spring Source portfolio. As I mentioned in my previous post, my goal is to provide a set of practical examples for Spring Scala users until project reference documentation will be published.

This time I would like to describe the possible ways of creating functional application contexts available in the latest milestone release.

First of all, let me demonstrate the example of simple FunctionalConfigApplicationContext. Quick reminder here - functional application config is a brand new way to define Scala-friendly Spring application context configurations by taking the advantage of Scala functions.
import org.springframework.scala.context.function.FunctionalConfigApplicationContext

class MyConfiguration extends FunctionalConfiguration {

  bean("serviceName") {
    new BusinessService(dao())
  }

  val dao = bean("daoName") {
    new JdbcDao()
  }

}
The simplest way to create application context from the configuration class presented above is to use the companion object of the FunctionalConfigApplicationContext class.
val context = FunctionalConfigApplicationContext[MyConfiguration]
val service = context[BusinessService]
If you want to build application context from multiple configuration classes, the companion FunctionalConfigApplicationContext object might be helpful again.
val context = FunctionalConfigApplicationContext(
  classOf[MyConfiguration],classOf[SomeOtherConfiguration])

val service = context[BusinessService]
At last, but not least, if you need a tighter control over the way the FunctionalConfigApplicationContext is built, you can create it using default constructor and then register the FunctionalConfiguration classes manually.
val context = new FunctionalConfigApplicationContext()
context.registerClass[MyConfiguration]
context.registerClasses(
  classOf[AnotherConfiguration], classOf[YetAnotherConfiguration])
context.refresh()

val service = context[BusinessService]
If you have in mind even better way to create functional configurations in Spring Scala, please just drop me a line. Or even better - issue pull request to the Spring Scala GitHub repository.

3 comments:

  1. Thanks , nice post . one question : getting services where we define the FunctionalConfigApplicationContext is pretty clear. But how can we inject beans/services/repositories in other classes ? do we need to recall the companion object of FunctionalConfigApplicationContext ?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Hi Avi,

    You have to define these classes as a Spring beans and use autowiring.

    Cheers!

    ReplyDelete