如何在应用程序中访问Play Framework 2.4 guice Injector? [英] How to access Play Framework 2.4 guice Injector in application?

查看:72
本文介绍了如何在应用程序中访问Play Framework 2.4 guice Injector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Play Framework 2.4中使用Guice Injector 类的 getInstance 方法,如何访问它?

I want to use the getInstance method of the Guice Injector class in Play Framework 2.4, how can I access it?

我使用Guice FactoryModuleBuilder 来实现一个在运行时返回另一个工厂的工厂!在返回工厂的第二级,我需要访问Play Guice Injector以使用反射手动获取对象,而不是 @Inject 注释。

I have used the Guice FactoryModuleBuilder for implementing a factory that returns another factory at runtime! At the second level of returning a factory I need to access the Play Guice Injector to get objects manually using reflection instead of @Inject annotation.

推荐答案

有很多方法。我用这个。

There are many ways. I use this one.

编辑:这与Play版本相关,< = 2.4:

This is relevant for Play versions which are <= 2.4:

Play.maybeApplication.map(_.injector.instanceOf[MyProdClass]).getOrElse(new MyDevClass)

Play.current.injector.instanceOf[MyClass]

对于> = 2.5的版本:

For versions which are >= 2.5:

import play.api.inject.Injector
import javax.inject.Inject

class MyService @Inject() (injector: Injector) ={
    val myClassInstance = injector.instanceOf[MyClass]
    //do stuff
}

这篇关于如何在应用程序中访问Play Framework 2.4 guice Injector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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