如何以编程方式获取Grails服务的实例?

Tho*_*ody 10 java grails spring

我有一个外部数据源,它将返回一个字符串,指示要使用的Grails服务的名称.

将服务名称作为字符串以编程方式获取此服务实例的语法是什么?

即.给定'GoogleWeather',给我一个GoogleWeatherService的实例.

谢谢!

小智 25

由于不推荐使用ApplicationHolder,这是另一种获取ApplicationContext的方法:

ApplicationContext ctx = Holders.grailsApplication.mainContext 
Run Code Online (Sandbox Code Playgroud)


Mic*_*ter 18

Grails文档描述了在servlet中获取服务的方法.如果您可以在上下文中获取相同的对象,这可能很有用:

ApplicationContext ctx = (ApplicationContext)ApplicationHolder.getApplication().getMainContext();
CountryServiceInt service = (CountryServiceInt) ctx.getBean("countryService");
String str = service.sayHello(request.getParameter.("name"));    
Run Code Online (Sandbox Code Playgroud)