ylima
ylima

Reputation: 440

Get a service bean from Grails Holders class

I'm trying to update a plugin to Grails 2.4. Thus I have to replace the deprecated ApplicationContext class by the newer Holders class.

But I'm having some problems getting a service bean from the Holders class.

Running the code below:

import grails.util.Holders;

def myService = Holders.grailsApplication.mainContext.myService

println myService
println myService.getClass()
println myService.serviceMethod()

It prints something like:

grails.plugin.my.MyService@1e5cd54d Exception thrown

java.lang.NullPointerException at ConsoleScript2.run(ConsoleScript2:6) at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)

It throws a NullPointerException when I call both: the "getClass" method and the "serviceMethod" method.

I tryed to see what's happening by debugging from eclipse too and I can observe "myService" variable being set to an object. When I click on it I can see it's String representation just like printed above. But I can't see anything inside the object. This service' class has member variables, but I can't see them on debug. It's like uf they were'nt there.

Can someone explain me what is going wrong?

Thanks

Upvotes: 1

Views: 1839

Answers (1)

Burt Beckwith
Burt Beckwith

Reputation: 75681

Don't use Holders, and avoid pulling in dependencies. Use dependency injection, it's a Good Thing.

Your src/groovy class is probably called from a controller, service, Quartz job, or some other Grails artifact that supports DI, right? If so, inject this service there, and when you call your src/groovy class, pass it as a method argument, or inject it once in a constructor or a setter.

Even if it's not called from a Grails artifact it's likely easy to get access to the service. E.g. a servlet can access the ServletContext and it's simple to access the ApplicationContext from there.

Upvotes: 3

Related Questions