【发布时间】:2019-05-30 17:48:40
【问题描述】:
我正在尝试通过 Play Framework 注入 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 类中创建一个空的构造函数,并创建一个构造函数链,但迄今为止未能成功地让缓存成功注入。
我做了下面的不同版本,用cached 初始化cache 变量或尝试通过cached:
class Setting @Inject()(cached: DefaultSyncCacheApi) {
val cache:DefaultSyncCacheApi
def this() {
this(cache)
}
}
有没有办法让 DI 使用这种设置,或者像工厂模式这样的东西会更好地工作吗?
【问题讨论】:
标签: scala dependency-injection playframework guice