加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – Play框架:依赖注入Action Builder

发布时间:2020-12-16 09:26:21 所属栏目:安全 来源:网络整理
导读:从Play Framework 2.4开始,就有可能使用依赖注入(使用Guice). 在我的ActionBuilders中使用对象(例如AuthenticationService)之前: object AuthenticatedAction extends ActionBuilder[AuthenticatedRequest] { override def invokeBlock[A](request: Request
从Play Framework 2.4开始,就有可能使用依赖注入(使用Guice).

在我的ActionBuilders中使用对象(例如AuthenticationService)之前:

object AuthenticatedAction extends ActionBuilder[AuthenticatedRequest] {
  override def invokeBlock[A](request: Request[A],block: (AuthenticatedRequest[A]) => Future[Result]): Future[Result] = {
    ...
    AuthenticationService.authenticate (...)
    ...
  }
}

现在,AuthenticationService不再是一个对象,而是一个类.我怎样才能在ActionBuilder中使用AuthenticationService?

解决方法

使用身份验证服务作为抽象字段在特征中定义操作构建器.然后将它们混合到您注入服务的控制器中.例如:

trait MyActionBuilders {
  // the abstract dependency
  def authService: AuthenticationService

  def AuthenticatedAction = new ActionBuilder[AuthenticatedRequest] {
    override def invokeBlock[A](request: Request[A],block(AuthenticatedRequest[A]) => Future[Result]): Future[Result] = {
      authService.authenticate(...)
      ...
    }
  }
}

和控制器:

@Singleton
class MyController @Inject()(authService: AuthenticationService) extends Controller with MyActionBuilders {    
  def myAction(...) = AuthenticatedAction { implicit request =>
    Ok("authenticated!")
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读