6

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?

doelleri
  • 19,232
  • 5
  • 61
  • 65
monda
  • 3,809
  • 15
  • 60
  • 84

1 Answers1

10

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.

micha
  • 47,774
  • 16
  • 73
  • 80
  • What do you mean by storing statful piece of information in the controller ? For example if I'm using the singleton and I have 4 methods which call Services with singleton scopes as well, there shouldn't be any problem with multiple users concurrently invoking the same method within the same controller ? For example uploadPhoto method/action of the same controller being called/accessed by multiple concurrent user. Can you please explain ? :) – AlexCon Jan 27 '14 at 16:49