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.
ctx."${beanName}"is added to theApplicationContextmetaclass so you can do stuff likedef userService = ctx.userService. It’s just a shortcut forctx.getBean('userService')so you could change your code toand it would be the same, but less magical.
Since you’re calling this from a controller or a service, I’d skip the
ServletContextHolderstuff and get the context by dependency-injecting thegrailsApplicationbean (def grailsApplication) and getting it viadef 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 simplyBut then it’s so simple that I wouldn’t bother with the helper class at all 🙂