Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should service layer classes be singletons?

I am using Spring framework. Should my service classes be created as singletons? Can someone please explain why or why not? Thanks!

like image 336
oym Avatar asked Jan 31 '10 19:01

oym


People also ask

Should service classes be singleton?

3 Answers. Show activity on this post. IMHO yes, services should not hold state and should therefore be made singleton.

Is @service 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.

Why @service is singleton?

A singleton service is a service for which only one instance exists in an application. For a sample application using the app-wide singleton service that this page describes, see the live example / download example showcasing all the documented features of NgModules.

Are @component singletons?

Yes, that is correct, @Component is a Spring bean and a Singleton. About singletons - spring beans are all in singleton scope by default.


1 Answers

Yes, they should be of scope singleton. Services should be stateless, and hence they don't need more than one instance.

Thus defining them in scope singleton would save the time to instantiate and wire them.

singleton is the default scope in spring, so just leave your bean definitions as they are, without explicitly specifying the scope attribute.

You can read more about scopes in the spring docs.

like image 107
Bozho Avatar answered Sep 24 '22 05:09

Bozho