Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Grails Service Class Is Singleton?

Tags:

grails

I came to know that Grails service class are of Singleton type. For what reason, the service classes are defined to be Singleton?

Thanks in advance.

like image 709
Ant's Avatar asked Jun 19 '12 05:06

Ant's


People also ask

Is service class a singleton?

In this case, service is a non-singleton nature. It will create multiple instances of a service. Every time a new instance of provided service will be created when a component is used inside another component. Service is being destroyed along with the component.

What are Grails services?

Services in Grails are the place to put the majority of the logic in your application, leaving controllers responsible for handling request flow with redirects and so on.


1 Answers

Grails services may be used with different scopes, not just singleton, by adding something like this to the class:

static scope = "flow"

From the manual:

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

The main reason for choosing singleton as the default is for better performance, both in reduced memory usage (only one instance is sitting around), and in reduced processing time, because you eliminate the overhead of creating a new object.

like image 100
OverZealous Avatar answered Oct 01 '22 12:10

OverZealous