定义 Scala Controller 时,使用 @Singleton 注释将类标记为单例:
@Singleton
class Application
https://docs.oracle.com/javaee/7/api/javax/inject/Singleton.html将 singleton 定义为“标识注入(inject)器仅实例化一次的类型”。不是遗传的。那么Scala玩依赖注入(inject)框架是依赖于Java依赖注入(inject)吗?
来自https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection “Play 支持基于 JSR 330(本页中描述)的运行时依赖注入(inject)和 Scala 中的编译时依赖注入(inject)。”使用 @Singleton 是否利用“基于 JSR 330 的依赖注入(inject)”,以便在“Scala 中使用编译时依赖注入(inject)”需要什么?
最佳答案
is Scala play dependency injection framework relying on Java dependency injection ?
是的,所以你需要在每个使用 DI 的文件中编写 import javax.inject._
。
你基本上需要做的是
· 将接口(interface)定义为trait
trait FooService {
def getBar(baz: String):Future[Bar]
}
・ 实现接口(interface)
class FooServiceImpl extends FooService {
def getBar(baz: String) = ???
}
・ 通过Module.scala(guice风格)绑定(bind)它们
class Module extends AbstractModule {
override def configure() = {
bind(classOf[FooService]).to(classOf[FooServiceImpl])
}
}
・使用它
class FooController @Inject()(fooService: FooService)(implicit exec: ExecutionContext) extends Controller {
def index = Action.async = {
fooService.getBar("fooBar").map{_.doWhatEverYouWant}
.....
}
}
正如你所看到的,当你使用这种DI方式时,你需要定义类参数。这就是你不能使用Scala object
而使用@Singleton
的原因相反。
关于scala - Scala play框架中@Singleton的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37379779/