Scala中的@Inject如何工作 [英] How does @Inject in Scala work

查看:240
本文介绍了Scala中的@Inject如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Play-Scala中的@Inject注释如何工作.它显然注入了一个依赖关系,但是我很好奇它是如何工作的.当我在类扩展控制器上使用它并将路由生成器设置为injectroutesgenerator时,似乎可以从那些类中自动创建对象,但是如何在其他上下文中使用它呢?

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?

我尝试过:

@Inject val mailer: MailerClient = null

但这似乎不起作用.将@Inject的东西(mailerClient,WS ets)直接@inject,而不是控制器类,有什么可能?

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?

推荐答案

看上去很近.将val更改为var,因为它不是最终的,需要在后期注入.

Looks close. Change val to var because it is not final and needs to be injected at a latter stage.

@Inject var mailer: MailerClient = null

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

I'd check also that the MailerClient library is mentioned as a dependency in the project configuration. You could try with WSClient instead as it's included by default in the template:

@Inject var ws: WSClient = null

尤其是据我所知,这一特定功能有效.

Especially as I know that this particular one works.

在GitHub上创建了 demo ,它是具有Play-Scala模板的index方法更改如下:

Created a demo on GitHub which is the Play-Scala template with the index method changed as follows:

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))
  }

}

这篇关于Scala中的@Inject如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆