scala – 在Play 2.4中使用DI,如何在“安全”特性中使用服务类?
发布时间:2020-12-16 19:11:26 所属栏目:安全 来源:网络整理
导读:这是一个 authorisation example from Play Documentation(版本2.0.4;我试图找到这个文件的更新版本,但不能): trait Secured { def username(request: RequestHeader) = request.session.get(Security.username) def onUnauthorized(request: RequestHeader
这是一个
authorisation example from Play Documentation(版本2.0.4;我试图找到这个文件的更新版本,但不能):
trait Secured { def username(request: RequestHeader) = request.session.get(Security.username) def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Auth.login) def withAuth(f: => String => Request[AnyContent] => Result) = { Security.Authenticated(username,onUnauthorized) { user => Action(request => f(user)(request)) } } def withUser(f: User => Request[AnyContent] => Result) = withAuth { username => implicit request => UserDAO.findOneByUsername(username).map { user => f(user)(request) }.getOrElse(onUnauthorized(request)) } } 总的来说这很简单,我想用这样的东西. 现在,在Play 2.4中,推荐的方法是不再使用单例(如上面的UserDAO),而是使用类和运行时DI(参见migration guide或DI docs). 例如,我的服务和存储库类定义如下: class AuthService @Inject()(accountRepo: AccountRepository) { } class AccountRepository { } 使用Play 2.4和DI时,在像Secured这样的特性中,建议/“正确”/最简单的方法是获取服务或DAO(例如我的案例中的AuthService,或doc示例中的UserDAO)? 或者您现在是否应该以不同于使用此类特征的方式实施控制器授权? 我可以按照以下方式开展工作: trait Secured { val authService = GuiceUtils.inject[AuthService] // ... } 使用这样的帮助: object GuiceUtils { lazy val injector = new GuiceApplicationBuilder().injector() def inject[T: ClassTag]: T = injector.instanceOf[T] } 但根据related question的答案:
如果这是真的,那么在这个用例中被认为是好的做法? 解决方法
我认为最简单的方法是在你的trait中声明authService但保持抽象,然后让扩展它的控制器处理注入(我相信这就是MessagesApi / I18nSupport注入的工作原理).所以你可以这样做:
trait Secured { val authService: AuthService ... } controller Application @Inject()(override val authService: AuthService) extends Controller with Secured { ... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |