How does @Inject in Scala work

时间:2015-06-20 09:39:56

标签: scala playframework dependency-injection playframework-2.0

I'm wondering how does @Inject annotation in Play-Scala works. It obviously injects a dependency, but I'm curious how is it working. When I was using it on class extending controller and set routes generator to injectroutesgenerator it seems to autmagically create objects from those classes, but how do I use it in other context?

I tried:

@Inject val mailer: MailerClient = null

But that doesn't seem to work. Are there any posibilities to @Inject things (that mailerClient, WS ets.) directly to a value, not to controller class?

1 个答案:

答案 0 :(得分:6)

看起来很近。将val更改为var,因为它不是最终版,需要在后期注入。

@Inject var mailer: MailerClient = null

我还要检查MailerClient库是否在项目配置中被提及为依赖项。您可以尝试使用WSClient,因为它默认包含在模板中:

@Inject var ws: WSClient = null

特别是我知道这个特定的作品。

更新

创建了一个demo on GitHub Play-Scala模板,index方法更改如下:

import play.api._
import play.api.libs.ws.WSClient
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class Application extends Controller {

  @Inject var ws: WSClient = null

  def index = Action.async {
    ws.url("http://google.com").get.map(r => Ok(r.body))
  }

}