dan*_*one 1 dependency-injection scala guice playframework
是否可以创建play.api.mvc.Controller具有依赖项注入参数的重载特征?
例如,假设我有几个定制的Action,它们需要注入依赖项AuthorizationService。我想这样写我的控制器:
class UserController extends CustomController {
def getUser(userID: String) = CustomAction {
...
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我无法弄清楚如何创建CustomController特性,从而不需要我在UserController中注入AuthorizationService。Guice有办法做到这一点吗?
您可以将字段注入到CustomController特征中。该字段不应为final,因此必须在Scala 中将其声明为var。
@Inject() var authService: AuthorizationService
Run Code Online (Sandbox Code Playgroud)
您还可以将注入的变量设为私有,并声明引用注入字段的公共变量。在这种情况下,val必须是惰性的,因为在实例化类之后进行注入。有关更多详细信息,请参见Guice文档。
@Inject() private var as: AuthorizationService = _
lazy val authService: AuthorizationService = as
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1342 次 |
| 最近记录: |