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.
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.
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.
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 classrequest
- A new service will be created per requestflash
- A new service will be created for the current and next request onlyflow
- In web flows the service will exist for the scope of the flowconversation
- In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flowssession
- A service is created for the scope of a user sessionsingleton
(default) - Only one instance of the service ever existsThe 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.
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