2016-07-28 30 views
2

我正在使用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。有人能幫助弄清楚有什麼問題嗎?在課堂上是否禁止使用注射劑?

回答

0

我會假設你注入對象在你的類簽名?

case class Foo @Inject()(barRepository:BarRepository, /* your fields */){ 
    /** some stuff **/ 
} 
+0

我不能這樣做,因爲類Foo表示業務邏輯的一些實體,在不同的地方使用了很多。此外,它看起來不像注入方法中的問題,我試圖將BarRepository作爲字段注入控制器,而不是使用構造函數,並且運行良好。我還試圖讓控制器成爲一個案例類,它仍然運作良好。 – alex

+0

我在播放框架中注入了一些問題,但是當發現錯誤時,播放的消息非常不準確。你有NullPointerException的StackTrace,你可以添加到你的問題? – sascha10000

+2

我想我發現了這個問題。我手動創建Foo類的實例,新操作符和Guice不以這種方式工作。綁定BarRepository Foo實例應該由Guice和BarRepository創建。 – alex

0

如果您不希望您的污染案例類的簽名與吉斯注入的註解和字段,然後簡單地添加上需要它,而不是方法隱式相關:

case class Foo(/*some fields*/) { 
    def bar1(someField: Int)(implicit barRepository: BarRepository) = { 
    // some code that interacts with barRepository 
    } 
} 

調用類將必須將BarRepository作爲隱式注入參數。例如。就像一齣戲控制器:

@Singleton 
class HomeController @Inject()(cc: ControllerComponents) 
(implicit barRepository: BarRepository) 
extends AbstractController(cc) { 
    def index() = Action { implicit request => 
    val foo = Foo("field") 
    val bar = foo.bar1 
    // ... 
    } 
}