views:

300

answers:

4

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

+6  A: 

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.

Bozho
Thanks. I am new to Spring, I know how to write a singleton class, but how do I set a "scope of singleton" using Spring?
es11
Oh I didnt see your comment about it being the default scope. Could you please explain to me where this scope is set and configured just so I can have an idea of how everything is wired? Thanks again.
es11
I added the link to my answer.
Bozho
Thanks! Good to know that I don't have to make any changes!
es11
+2  A: 

Spring is easier to use if you stick with singleton-scoped beans. Singletons are its "default position", if you like. Yes, it supports other scopes (using scope="xyz" in the XML file), but it makes things harder to use and hurts performance.

Essentially, unless you have a good reason to do otherwise, stick with singletons.

skaffman
A: 

You need mostly singletons. (Spring default.) Singletons must me thread-safe because parallel requests will use the same single instance. In fact, they must be completely stateless because it can be destroyed and recreated at any time.

If you need to keep track of state inside of your bean (you should not, this should be in the database or stored in the request) you will get many instances of the same type of bean, memory usage goes up with the number of requests whereby with singletons you will still have just one instance.

Even if you scope you beans to a request, they must still need be at least thread-safe (requests coming from the same browser at the same time).

sibidiba
Spring singleton beans can *not* be created and destroyed at any time, I don't know where you got that from (maybe you're confusing them with EJB session beans). Also, mutable state within a Spring singleton is absolutely fine, you just need to be aware of what operations can be done on that shared state.
skaffman
A: 

so if a service class is a singleton and you're using the service class in a web context, does that mean one instance of the service class would be handling all the requests that is hitting the service class? If so, is that efficient?

Luke