如何在创建注入 class 实例时注入配置实例?
how to inject an instance of configuration when creating instance of the injected class?
我有一个简单的情况:
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
谢谢!
首先,您应该确定依赖注入是否真的是您所需要的。 DI 的基本思想:不是工厂或对象自己创建新对象,而是在外部传递依赖项,并将实例化问题传递给其他人。
如果你依赖框架,你应该全力以赴,这就是为什么无法将 new
与 DI 一起使用的原因。你不能 pass/inject a class 到 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]
...
}
在框架帮助下扩展的简单情况。所以,你真的应该考虑其他可能性。也许在您的情况下将配置作为隐式参数传递会更好?
有关使用 guice 进行依赖注入的信息,请查看:
ScalaDependencyInjection with play and Guice wiki
我有一个简单的情况:
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
谢谢!
首先,您应该确定依赖注入是否真的是您所需要的。 DI 的基本思想:不是工厂或对象自己创建新对象,而是在外部传递依赖项,并将实例化问题传递给其他人。
如果你依赖框架,你应该全力以赴,这就是为什么无法将 new
与 DI 一起使用的原因。你不能 pass/inject a class 到 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]
...
}
在框架帮助下扩展的简单情况。所以,你真的应该考虑其他可能性。也许在您的情况下将配置作为隐式参数传递会更好?
有关使用 guice 进行依赖注入的信息,请查看: ScalaDependencyInjection with play and Guice wiki