【发布时间】:2019-10-17 12:58:17
【问题描述】:
我正在尝试在 Scala 中进行方法或字段注入。我正在使用 Play Framework,它使用 Guice 进行注入。我尝试过像这样的字段注入:
@Inject val cache: DefaultSyncCacheApi = null
喜欢详细的here,但每当我尝试测试它时,我都会得到一个NullPointerException。我也尝试过方法注入,例如:
@Inject
def method(id: String, cache: DefaultSyncCacheApi): Boolean = {
val cachedItem = cache.get(id)
cachedItem.isDefined
}
也无济于事。我也必须从另一个地方传入缓存。
我也尝试过使用重载方法,分别注入,如:
val cache: DefaultSyncCacheApi //this will not work if it is not an abstract class
@Inject //either injecting here
def methodA(id: String): Boolean = {
methodB(string, cache)
}
@Inject //or injecting here
def methodB(id: String, cache: DefaultSyncCacheApi): Boolean = {
//same logic as 'method' above
}
无济于事。是否有明确的方法来进行方法或字段注入而不会导致 NPE?
【问题讨论】:
标签: scala dependency-injection playframework guice