我見過這樣的代碼在app/Global.scala
,這是由我的同事寫在playframework中設置像這樣的GLOBAL變量是否是一個好習慣?
import java.lang.reflect.Constructor
import securesocial.core.RuntimeEnvironment
import securesocial.core.providers._
import securesocial.core.providers.utils.Mailer
import services.UserService
import scala.collection.immutable.ListMap
object Global extends play.api.GlobalSettings {
/**
* The runtime environment for this app.
*/
object MyRuntimeEnvironment extends RuntimeEnvironment.Default[User] {
// override lazy val routes = new CustomRoutesService()
override lazy val userService: UserService = new UserService()
lazy val MailTemplates: MailTemplates = new MailTemplates(this)
override lazy val mailer: Mailer = new Mailer(MailTemplates)
// override lazy val eventListeners = List(new MyEventListener())
override lazy val providers = ListMap(
// oauth 2 client providers
include(new FacebookProvider(routes, cacheService, oauth2ClientFor(FacebookProvider.Facebook))),
// username password
include(new UsernamePasswordProvider(userService, avatarService, passwordHashers))
)
}
/**
* An implementation that checks if the controller expects a RuntimeEnvironment and
* passes the instance to it if required.
*
* This can be replaced by any DI framework to inject it differently.
*
* @param controllerClass
* @tparam A
* @return
*/
override def getControllerInstance[A](controllerClass: Class[A]): A = {
val instance = controllerClass.getConstructors.find { c =>
val params = c.getParameterTypes
params.length == 1 && params(0) == classOf[RuntimeEnvironment[User]]
}.map {
_.asInstanceOf[Constructor[A]].newInstance(MyRuntimeEnvironment)
}
instance.getOrElse(super.getControllerInstance(controllerClass))
}
}
有誰認爲這是合適的設置服務在全球playframework值?