【发布时间】:2016-06-02 01:27:28
【问题描述】:
我在我的控制器类中使用依赖注入进行了实例化。当我尝试在其他地方使用 @inject 注释使用该对象时,我得到空值。这是我的代码框架。
@singleton
class ServiceClient(ws: WSClient, config: Configuration) {
def get response() {...}
}
class App @Inject()(client: ServiceClient) extends Controller {
def getItems = Action {
Obj()
}
}
case class Obj() {
@Inject
var client: ServiceClient = _
def doStuff() {
client.getResponse() //client is null so get null pointer exception.
....
}
}
Obj 中的@Inject 似乎从来没有工作过。我的客户对象始终为空。 (我不想将客户端作为参数传递给 Obj。)我的期望是在控制器中创建的 ServiceClient 对象应该被注入到 Obj() 中。我做错了什么?
更新
将 Obj 注入控制器不是一种选择。 (在我的应用程序中,Obj 在运行时实例化了我的一些复杂规则,使用反射)。另外我不想在 Obj 中注入构造函数。 我正在寻找控制器外的 ServiceClient 字段注入。
更新2
我能够使用
解决问题var client: ServiceClient = play.api.Play.current.injector.instanceOf(classOf[ServiceClient])
在 Obj 类中。 但是,play.api.Play.current 在 play 2.5 中已被弃用,所以我仍然有点被警告所困扰。
【问题讨论】:
标签: scala dependency-injection playframework-2.1