【问题标题】:Play Framework: Inject multiple dependencies using constructor injection in the controllerPlay Framework:在控制器中使用构造函数注入注入多个依赖项
【发布时间】:2015-07-19 23:00:58
【问题描述】:

在 Scala 中使用 Play Framework(2.4.x,提供基于 guice 的 DI 开箱即用)中的控制器的构造函数注入注入多个依赖项的正确方法是什么?

例如,

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

上面说只能注入一个或不能注入构造函数 arg 不能编译。

无法找到有关如何使其正常工作的任何好的参考资料。任何帮助表示赞赏。谢谢。

【问题讨论】:

    标签: scala playframework dependency-injection


    【解决方案1】:

    您可能需要在参数前添加val

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

    还要检查您是否有正确的导入:

    import javax.inject.Inject
    

    Here你也可以找到一个有多个依赖的例子,也许它会有所帮助。

    【讨论】:

      【解决方案2】:

      您的代码是正确的。除此之外,您需要在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]
        )
      }
      

      For the offical documentation see this link.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多