我正在使用Scala編寫Play 2.5應用程序。我有以下一段代碼:Google Guice在scala case類中的域注入
@ImplementedBy(classOf[BarRepositoryImpl])
trait BarRepository {
def bar = //some actions
}
class BarRepositoryImpl extends BarRepository
case class Foo(/*some fields*/) {
@Inject private var barRepository: BarRepository = null
def foo1 = {
val a = barRepository.bar //here barRepository is always null
// some actions with 'a' and returning some result which depends on 'a'
}
}
我也有一個控制器,我注入BarRepository爲好,但通過構造有一切正常,而在上線VAL A = barRepository.bar我得到的類Foo一個NullPointerException。有人能幫助弄清楚有什麼問題嗎?在課堂上是否禁止使用注射劑?
我不能這樣做,因爲類Foo表示業務邏輯的一些實體,在不同的地方使用了很多。此外,它看起來不像注入方法中的問題,我試圖將BarRepository作爲字段注入控制器,而不是使用構造函數,並且運行良好。我還試圖讓控制器成爲一個案例類,它仍然運作良好。 – alex
我在播放框架中注入了一些問題,但是當發現錯誤時,播放的消息非常不準確。你有NullPointerException的StackTrace,你可以添加到你的問題? – sascha10000
我想我發現了這個問題。我手動創建Foo類的實例,新操作符和Guice不以這種方式工作。綁定BarRepository Foo實例應該由Guice和BarRepository創建。 – alex