问题
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)
}
}
}
- In BootStrap.groovy, inject grailsApplication like this:
def grailsApplication
- Make a call like mine above, substituting your own package name - to avoid messing around with plugins' classes.
- 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