【问题标题】:Dependency Injection to Play Framework 2.5 modulesPlay Framework 2.5 模块的依赖注入
【发布时间】:2016-10-04 23:21:57
【问题描述】:

我有一个具有以下签名的模块类:

class SilhouetteModule extends AbstractModule with ScalaModule {

我想注入配置:

class SilhouetteModule @Inject() (configuration: Configuration) extends AbstractModule with ScalaModule {

但它失败并出现以下错误。

No valid constructors
Module [modules.SilhouetteModule] cannot be instantiated.

Play 文档提到

大多数情况下,如果你在创建组件的时候需要访问Configuration,你应该将Configuration对象注入到组件本身或者...

,但我不知道如何成功。那么问题来了,如何在 Play 2.5 中将依赖注入到模块类中?

【问题讨论】:

  • 您引用的部分上面的示例没有使用@Inject 注释,它只是说明并表明您可以添加构造函数参数。你试过吗?
  • 什么是ScalaModuleAbstractModule?模块实际上不应该具有任何构造函数参数。它们应该为可能需要(或不需要)注入东西的类提供绑定。你到底想在这里做什么?

标签: scala playframework dependency-injection


【解决方案1】:

有两种解决方案可以解决您的问题。

第一个(也是更直接的一个): 不要扩展com.google.inject.AbstractModule。而是使用play.api.inject.Module。扩展它会强制您覆盖def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]]。在该方法中,您可以进行所有绑定,并将配置作为方法参数插入。

第二个(也是更灵活的一个): 根据您对要注入的组件的需求,您可以为要绑定的组件定义一个提供程序。在那个提供者中,你可以注入任何你想要的东西。例如

import com.google.inject.Provider

class MyComponentProvider @Inject()(configuration:Configuration) extends Provider[MyComponent] {
    override def get(): MyComponent = {
        //do what ever you like to do with the configuration
        // return an instance of MyComponent
    }
}

然后你可以在你的模块中绑定你的组件:

class SilhouetteModule extends AbstractModule {
    override def configure(): Unit = {
        bind(classOf[MyComponent]).toProvider(classOf[MyComponentProvider])
    }
}

第二个版本的优点是你可以注入任何你喜欢的东西。在第一个版本中,您“只是”获得了配置。

【讨论】:

【解决方案2】:

从以下位置更改您的构造函数签名:

class SilhouetteModule @Inject() (configuration: Configuration) extends AbstractModule with ScalaModule

到:

class SilhouetteModule(env: Environment, configuration: Configuration) extends AbstractModule with ScalaModule

查看此处了解更多信息: https://github.com/playframework/playframework/issues/8474

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多