Changing the behaviour/Scope of Services in Grails.

15 / Sep / 2010 by Chandan Luthra 0 comments

Sometimes our services are so tightly bound with the Controllers that we actually think that a new Service instance should be get created on every request or the member variables in the services can be defined only for the current user. But by default the Services are “singleton” scoped which means that clients of a service only ever use a single instance (a singleton) of the service. We should be very careful about storing state in a service and in fact we should never store any state in the Service.

The default “singleton” behavior of the service can be overridden by adding a static property “scope” to your Service Class.


class MyService {
	static scope = "session"

By adding a static property scope = “session”, we can actually store info related to current user within the session.

Grails provide us following 7 scopes (including singleton) through which we can change the scope of a Service.

  1. prototype – A new service is created every time it is injected into another class
  2. request – A new service will be created per request
  3. flash – A new service will be created for the current and next request only
  4. flow – In web flows the service will exist for the scope of the flow
  5. conversation – In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flows
  6. session – A service is created for the scope of a user session
  7. singleton (default) – Only one instance of the service ever exists

Note: If your service is “flash”, “flow” or “conversation” scoped then it will need to implement and can only be used in the context of a Web Flow.

Hope it helps you and saves your time.


~Chandan Luthra


Leave a Reply

Your email address will not be published. Required fields are marked *