Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically select a service in Grails

From my controller I would like to dynamically select a service based on a parameter.

Currently I have a base service and some other services that extent this base service. Based on the parameter I call a class that does creates a bean name based on the param and eventually calls the following:

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA

class Resolver {
    def ctx

def getBean(String beanName) {
    if(!ctx) {
        ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
    }
    return ctx."${beanName}"
}

}

This returns the service I want. However I feel rather dirty doing it this way. Does anyone have a better way to handle getting a service (or any other bean) based on some parameter?

Thank you.

like image 846
Jeremy Avatar asked Dec 19 '12 16:12

Jeremy


1 Answers

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 :)

like image 132
Burt Beckwith Avatar answered Nov 09 '22 03:11

Burt Beckwith