Default scope for Grails controller is prototype
i.e. a new controller will be created for each request (recommended for actions as Closure properties)
Two more scopes are supported by controllers:
session
- One controller is created for the scope of a user session
singleton
- Only one instance of the controller ever exists (recommended for actions as methods)
When should I use which scope? When can I make a decision of changing the scope? In what scenario?
Prototype
and session
scope means that you can store request/session specific state within controller fields. This however is not a recommended practice and should be avoided.
If you follow common practice and avoid state in controllers you can easily go with the singleton
scope (which is the default in Spring Web MVC controllers).
If you have state in your controllers you have to go with prototype
or session
scope.
In general I would recommend not to mix different scopes for controllers. It can be a very painful experience if you accidently add a stateful field to a singleton controller because you are used to prototype
scope. You won't notice this bug until multiple concurrent requests/sessions access the same field and everything breaks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With