Play框架:在控制器中使用构造函数注入注入多个依赖项



在Play框架(2.4)中使用构造函数注入控制器的正确方法是什么?(它在Scala中提供了基于向导的开箱即用的DI) ?

例如,

class ExampleController @Inject() (serviceOne: ServiceOne, serviceTwo: ServiceTwo) extends Controller {
}

上面的代码不会说明只能注入一个或不能注入构造函数参数。

无法找到任何好的参考资料,关于如何得到这个工作。任何帮助都是感激的。谢谢。

您可能需要在参数前加上val:

class ExampleController @Inject() (val serviceOne: ServiceOne, val serviceTwo: ServiceTwo) extends Controller {

并检查是否导入正确:

import javax.inject.Inject

你也可以在这里找到一个有多个依赖的例子,也许它有帮助。

代码是正确的。除此之外,您需要在application.conf

中配置module
play.modules.enabled += "com.example.HelloModule"

然后在这个Module中,你需要描述你的依赖注入类:

import play.api.inject._
class HelloModule extends Module {
  def bindings(environment: Environment,
               configuration: Configuration) = Seq(
    bind[Hello].qualifiedWith("en").to[EnglishHello],
    bind[Hello].qualifiedWith("de").to[GermanHello]
  )
}

有关官方文档,请参阅此链接

最新更新