Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an instance of a Grails service programmatically?

I have an external data source, which will return a string indicating the name of a Grails service to use.

What's the syntax to get an instance of this service programatically given the name of the service as a String?

ie. given 'GoogleWeather', give me an instance of GoogleWeatherService.

Thanks!

like image 879
Thody Avatar asked Feb 16 '10 21:02

Thody


2 Answers

The Grails documentation describes a way to get a service when in a servlet. This might be useful, if you can obtain the same objects in your context:

ApplicationContext ctx = (ApplicationContext)ApplicationHolder.getApplication().getMainContext();
CountryServiceInt service = (CountryServiceInt) ctx.getBean("countryService");
String str = service.sayHello(request.getParameter.("name"));    
like image 56
Michael Easter Avatar answered Oct 23 '22 22:10

Michael Easter


Since ApplicationHolder has been deprecated, this is another way to get the ApplicationContext:

ApplicationContext ctx = Holders.grailsApplication.mainContext 
like image 28
Marcin Avatar answered Oct 23 '22 22:10

Marcin