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?
答案 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))
}
}