如何在Grails中动态选择一项服务 [英] How to dynamically select a service in Grails
问题描述
在我的控制器中,我希望根据参数动态选择服务。
目前我有一个基本服务和一些其他服务来扩展这个基本服务。根据参数我调用一个类,该类创建一个基于param的bean名称,并最终调用以下内容:
import org .codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA
class Resolver {
def ctx
$ b $ getBean(String beanName){
if(!ctx){
ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
}
返回ctx。$ {beanName}
}
}
这会返回我想要的服务。不过,我觉得这样做很脏。有没有人有更好的方式来处理基于某些参数获取服务(或任何其他bean)?
谢谢。
ctx。$ {beanName}
被添加到 ApplicationContext
metaclass,所以你可以做一些像 def userService = ctx.userService
的东西。它只是 ctx.getBean('userService')
的一个快捷方式,因此您可以将代码更改为
return ctx.getBean(beanName)
它会是一样的,但不那么神奇。
由于您是从控制器或服务调用它的,我会跳过 ServletContextHolder
stuff并通过依赖注入 grailsApplication
bean( def grailsApplication
)并通过<$ c获取它$ c> def ctx = grailsApplication.mainContext 。然后将它传递给这个帮助类(记住Spring的大范例是依赖注入,而不是老派的依赖拉),然后它就会简单地变成:
class Resolver {
def getBean(ctx,String beanName){
ctx.getBean(beanName)
}
}
$ b但是这很简单,我根本不用打扰辅助类:)
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 theApplicationContext
metaclass so you can do stuff likedef userService = ctx.userService
. It's just a shortcut forctx.getBean('userService')
so you could change your code toreturn 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 thegrailsApplication
bean (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 simplyclass 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 :)
这篇关于如何在Grails中动态选择一项服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!