我正在尝试通过Play框架注入ehcache。我将其注入到同伴类中,但是该类正在其他位置以及同伴对象的抽象类中实例化。我不想将任何东西注入到抽象类中,因为它已在其他地方使用。
例如,基本上是通过以下方式设置伴随类和对象的(删除了一些逻辑和扩展以提高可读性):
class Setting @Inject()(cached: DefaultSyncCacheApi) {
def isCached(id:String): Boolean = {
val cachedItem = cached.get(id)
cachedItem.isDefined
}
}
object Setting {
def getId(id:String): Setting = {
val setting = new Setting //I know this doesn't work
if (setting.isCached(id)) {
//retrieval logic
}
setting
}
}
这是要实例化的抽象类:
abstract class UsingSettingAbstract {
def methodUsingSetting(): String = {
val setting = new Setting
val str = new String
//logic in here
str
}
}
我尝试使用def this() { }
在Setting类中创建一个空的构造函数,并创建一个构造函数链,但是到目前为止,成功地将缓存成功注入还没有成功。
我做了下面的不同版本,用cache
初始化cached
变量或尝试通过cached
:
class Setting @Inject()(cached: DefaultSyncCacheApi) {
val cache:DefaultSyncCacheApi
def this() {
this(cache)
}
}
是否有一种方法可以使DI与该设置一起使用,或者像工厂模式这样的方法会更好?
答案 0 :(得分:0)
使用guice,您可以将任何创建的实例传递给注入器的“ requestInjection()”方法。这将触发该实例上的方法和字段注入。
只要可以使用注射器,就可以完成注射。