有什么方法可以在没有控制器的情况下直接从模型或其他 class 使用 Inject 吗?

Is there any way to use Inject directly from model or other class without controller?

我刚开始使用 playframework 2.5 scala。

我找到的关于Inject用法的例子仅来自controller.Like:

class SampController @Inject()(service:Service) extends Controller{
  def index = Action{implict request =>
    ..
    sample.exec(service)
    ..
  }
}

class Sample{
  def exec(service:Service) = {
    ...
  }
}

但是,我想直接从 "Sample" 注入对象。 有什么办法吗?

class SampController extends Controller{
  def index = Action{implict request =>
    ...
    sample.exec()
    ...
  }
}

class Sample{
  def exec = {
     val service:Service = #Any way to get injected object here?
     ...
  }
}

谢谢。

您可以在 Sample 上使用 guice 依赖注入并将 Service 注入其中,然后将 Sample 注入控制器。

@Singleton
class SampController @Inject() (sample: Sample) extends Controller {
  def index = Action { implict request =>
    ...
    sample.exec()
    ...
  }
}

@Singleton
class Sample @Inject() (service: Service) {
   def exec = {
    service.doSomething()
    ...
  }
}