2010-10-24 187 views
0

我在使用Grails中的服務使用依賴注入時遇到問題。Grails依賴注入問題

class ExampleService{ 

    def example2Service 
    def example3Service 

    def method1(){ 
     def result = example2Service.method2() 
    } 

} 

class ExampleService{ 
    def example3Service 

    def method2(){ 

     def result = example3Service.method3() 
     return result 
    } 

} 

class Example3Service{ 

    def method3(){ 
     return true 
    } 

} 

基本上在Example2Service,我試圖調用方法3在Example3Service時得到一個空指針異常。

我希望得到任何幫助比任何人都可以給我這個問題

感謝

+1

你檢查明顯的事實:即該test3Service名爲Test3Service並適當命名的文件? – hvgotcodes 2010-10-24 22:08:10

+0

是的,它的名字是正確的。如果我從TestService調用它,但是我需要能夠從Test2Service調用方法 – MTH 2010-10-25 04:18:04

回答

1

依賴注入需要進行初始化。 (這同樣適用於其它類型的運行時元編程的,就像其save()validate()方法增強域的類。)

  • 正在從grails run-app命令運行

    Grails應用程序將被初始化

  • 在部署到Web服務器後運行
  • 正在從grails test-app命令運行(集成測試,僅; 單元測試不會觸發初始化)。

所涉類

  • 執行單個Groovy的文件初始化(即,通過使用groovygroovysh,或groovyConsole
  • 或執行單元測試時。

以下爲集成測試應該工作:

class Test2ServiceTests extends GroovyTestCase { 
    def test2Service 

    void testMethod2() { 
     assert test2Service.method2() == true 
    } 
} 
+0

我不寫單元測試或集成測試。代碼示例只是爲了說明我遇到的問題。 – MTH 2010-10-25 09:17:56

+0

可能您的問題沒有正確隔離,您的原始問題是缺少必需的信息。 – robbbert 2010-10-25 11:22:58