如何在创建注入类的实例时注入配置实例?

时间:2017-06-28 23:59:02

标签: java scala dependency-injection guice

我有一个简单的情况:

class MyClass @Inject() (configuration: Configuration) {

    val port = configuration.get[String]("port")

    ...

}

现在我想在其他对象中使用MyClass:

object Toyota extends Car {

  val myClass = new MyClass(???)

  ...

}

但是我不知道当我使用MyClass时我给它配置了一个注释的配置实例,它将在MyClass实例化时被注入..

我正在使用play2.6 / juice / scala

谢谢!

1 个答案:

答案 0 :(得分:2)

首先,您应该确定依赖注入是否真正符合您的需求。 DI的基本思想:不是工厂或对象本身创建新对象,而是从外部传递依赖关系,并将实例化问题传递给其他人。

如果您依赖框架,您可以全力以赴,这就是为什么无法使用 new 和DI。你不能将一个类传递/注入到scala对象中,这是你可以做的草案:

Play / guice需要一些准备。

注射模块告诉guice如何创建对象(如果注释不能这样做,或者想在一个地方进行)。

class InjectionModule extends AbstractModule {
  override def configure() = {
    // ...
    bind(classOf[MyClass])
    bind(classOf[GlobalContext]).asEagerSingleton()
  }
}

注入进样器以便能够访问它。

class GlobalContext @Inject()(playInjector: Injector) {
  GlobalContext.injectorRef = playInjector
}

object GlobalContext {
  private var injectorRef: Injector = _

  def injector: Injector = injectorRef
}

指定要启用的模块,因为可以有多个模块。

// application.conf
play.modules.enabled += "modules.InjectionModule"

最后是客户端代码。

object Toyota extends Car {

  import GlobalContext.injector

  // at this point Guice figures out how to instantiate MyClass, create and inject all the required dependencies
  val myClass = injector.instanceOf[MyClass]

  ...

}

通过框架帮助扩展了一个简单的情况。所以,你应该考虑其他可能性。也许最好将configs作为隐含参数传递给你的情况?

对于使用guice的依赖注入,请查看: ScalaDependencyInjection with playGuice wiki

相关问题