Why should grails actions be declared as methods i

2019-01-11 07:04发布

问题:

In grails 2.0 whats new http://grails.org/doc/2.0.0.RC1/guide/introduction.html#whatsNew
it says:
1.1.3 Web Features Controller Actions as Methods It is now possible to define controller actions as methods instead of using closures as in previous versions of Grails. In fact this is now the preferred way of expressing an action.
For example:

// action as a method
def index() {
}
// action as a closure
def index = {

}

Why is this important? What difference does it make?

UPDATE: I found this discussion that talks a lot about scope and some pretty hairy stuff. http://grails.1312388.n4.nabble.com/Controller-actions-methods-or-closures-was-Re-grails-dev-Statically-typed-meta-programing-td3048287.html

I guess my question could also be this: what advantage do closures have for the actions?

回答1:

The answer is here

From above link

Leveraging methods instead of Closure properties has some advantages:

  1. Memory efficient
  2. Allow use of stateless controllers (singleton scope)
  3. You can override actions from subclasses and call the overridden superclass method with super.actionName()
  4. Methods can be intercepted with standard proxying mechanisms, something that is complicated to do with Closures since they're fields.

Also there's a similar groovy question here that has some more details