mh377
mh377

Reputation: 1856

Grails Dependency Injection Problem

I am having problems when using dependency injection with Services in 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
    }

}

Basically in Example2Service, I am getting a Null Pointer Exception when trying to call method3 in Example3Service.

I would appreciate any help than anybody can give me with this issue

thanks

Upvotes: 0

Views: 1359

Answers (1)

robbbert
robbbert

Reputation: 2193

Dependency Injection needs to be initialized. (The same applies to other kinds of runtime meta programming, like augmenting Domain classes with their save() and validate() methods.)

A Grails application will be initialized when

  • being run from the grails run-app command
  • being run after having been deployed to a web server
  • being run from the grails test-app command (integration tests, only; unit tests do not trigger initialization).

Involved classes are not initialized when

  • executing a single Groovy file (i.e., by using groovy, groovysh, or groovyConsole)
  • or when executing a unit test.

The following as an integration test should work:

class Test2ServiceTests extends GroovyTestCase {
    def test2Service

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

Upvotes: 1

Related Questions