如何在 Grails 3 中的自定义标记库 class 中获取服务 bean

How to get a service bean inside a custom tag library class in Grails 3

我想从自定义标记库中的应用程序上下文中获取服务 bean。我将从自定义标签属性中获取服务名称。

这是我之前使用的代码。

class CustomTagLib {
    static defaultEncodeAs = [taglib:'html']
    //static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
    def selectList = { attrs ->
        try{
            String servName=attrs.service
            String servMethod=attrs.method
            ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext())
            def myservice=ctx."${servName}"

            attrs.from = myservice.invokeMethod(servMethod,null);
            out << g.select( attrs )
        }catch(Exception e){
            println("Exception in CustomTagLib in method selectList:"+e)
        }
    }
}

此代码适用于 Grails 2.3 版本,但不适用于版本 3。 请帮我找出解决办法。

尝试以下操作:

import grails.util.Holders

def myservice = Holders.getApplicationContext().getBean( servName )

其中 servName 是您的服务名称,首字母小写,其余为驼峰式