How to dynamically select a service in Grails How to dynamically select a service in Grails spring spring

How to dynamically select a service in Grails


ctx."${beanName}" is added to the ApplicationContext metaclass so you can do stuff like def userService = ctx.userService. It's just a shortcut for ctx.getBean('userService') so you could change your code to

return ctx.getBean(beanName)

and it would be the same, but less magical.

Since you're calling this from a controller or a service, I'd skip the ServletContextHolder stuff and get the context by dependency-injecting the grailsApplication bean (def grailsApplication) and getting it via def ctx = grailsApplication.mainContext. Then pass it into this helper class (remember the big paradigm of Spring is dependency injection, not old-school dependency-pulling) and then it would be simply

class Resolver {   def getBean(ctx, String beanName) {      ctx.getBean(beanName)   }}

But then it's so simple that I wouldn't bother with the helper class at all :)