Out of the box, Play provides dependency injection support based on JSR 330. The default JSR 330 implementation that comes with Play is Guice, but other JSR 330 implementations can be plugged in.
class SkGuiceApplicationLoader extends GuiceApplicationLoader {
override protected def overrides(context: Context): Seq[GuiceableModule] = {
super.overrides(context) ++ Seq[GuiceableModule](
bind[Injector].to[SkInjector]
)
}
}
class SkInjector @Inject() (injector: com.google.inject.Injector) extends GuiceInjector(injector) {
/**
* Get an instance of the given class from the injector.
*/
override def instanceOf[T](implicit ct: ClassTag[T]) = {
instanceOf(ct.runtimeClass.asInstanceOf[Class[T]])
}
/**
* Get an instance of the given class from the injector.
*/
override def instanceOf[T](clazz: Class[T]) = {
var bean: Option[T] = None
if(classOf[Controller].isAssignableFrom(clazz)) {
//BaseGlobal.ctx is my spring context. You can change it to your context.
bean = Option(BaseGlobal.ctx.getBean(clazz))
}
if(bean.isEmpty) {
bean = Option(super.instanceOf(clazz))
}
bean.fold(null.asInstanceOf[T])(x => x)
}
/**
* Get an instance bound to the given binding key.
*/
override def instanceOf[T](key: BindingKey[T]) = {
var bean: Option[T] = None
if(classOf[Controller].isAssignableFrom(key.clazz)) {
bean = Option(BaseGlobal.ctx.getBean(key.clazz))
}
if(bean.isEmpty) {
bean = Option(super.instanceOf(key))
}
bean.fold(null.asInstanceOf[T])(x => x)
}
}
play.application.loader = "common.play.inject.SkGuiceApplicationLoader"