Add methods to controllers

纵然是瞬间 提交于 2019-12-23 05:32:08

问题


In a Grails application I would like to add a foo() method to all my controller classes. I know that I can do this inside a plugin's doWithDynamicMethods closure using code like:

application.controllerClasses.toList()*.metaClass*.foo = { println 'foo called' }

However, I don't want to create a plugin just for this purpose. Is there anywhere else I can do this. I suspect it might be possible within the init closure of BootStrap.groovy, but I don't know how to get access to the GrailsApplication instance in this closure.

Thanks, Don


回答1:


def grailsApplication = org.codehaus.groovy.grails.commons.ApplicationHolder.application



回答2:


The question was asked a long time ago, so my answer might not have been possible back then - but now it's April 2014. This code shows the most straightforward way of adding a method to all your controllers (from within BootStrap.init):

grailsApplication.controllerClasses.each { controllerClass ->
    if (controllerClass.clazz.name.contains("org.idurkan.foo")) {
        controllerClass.metaClass.respondError = { String message, int status = 404 ->
            response.status = status
            render([errorMessage: message] as JSON)
        }
    }
}
  1. In BootStrap.groovy, inject grailsApplication like this: def grailsApplication
  2. Make a call like mine above, substituting your own package name - to avoid messing around with plugins' classes.
  3. Now in any controller you can use the repondError closure (invoke it like a method).

Note this does not add an action! It's just a utility closure/method available in every controller.




回答3:


class BootStrap {
    def grailsApplication

    def init = { servletContext ->
        ...
    }
}


来源:https://stackoverflow.com/questions/1049418/add-methods-to-controllers

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