2010-10-24 164 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