How to dynamically select a service in Grails

*爱你&永不变心* 提交于 2019-12-08 17:00:26

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/13956316/how-to-dynamically-select-a-service-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!