在 Scala Play 框架中使用@Singleton



当定义 Scala 控制器时,将类标记为单例时,请使用 @Singleton 注释:

@Singleton
class Application

https://docs.oracle.com/javaee/7/api/javax/inject/Singleton.html 将单一实例定义为"标识注入器仅实例化一次的类型。那么Scala播放依赖注入框架是否依赖于Java依赖注入?

从 https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection"Play支持基于JSR 330的运行时依赖注入(在本页中描述)和Scala中的编译时依赖注入。使用@Singleton利用"基于 JSR 330 的依赖注入",所以使用"Scala 中的编译时依赖注入"需要什么?

是依赖于Java的Scala播放依赖注入框架 依赖注入 ?

是的,所以你需要写import javax.inject._你使用DI的每个文件。

你基本上需要做的是

・ 将接口定义为trait

trait FooService {
  def getBar(baz: String):Future[Bar]
}

・实现接口

class FooServiceImpl extends FooService {
  def getBar(baz: String) = ???
}

・通过模块绑定它们.scala(guice样式)

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的原因。

编译时和运行时 DI 之间的主要区别在于,使用运行时 DI,您将不知道您的依赖项是否会被连接和满足,直到您运行应用程序(即,您将收到运行时错误而不是编译时错误)

有关

Play的编译时DI支持的更多信息,我强烈建议您查看有关它的官方文档。

最新更新