问题
I am using Spring framework. Should my service classes be created as singletons? Can someone please explain why or why not? Thanks!
回答1:
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.
回答2:
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.
回答3:
You need mostly singletons. (Spring default.) Singletons must be 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).
来源:https://stackoverflow.com/questions/2173006/should-service-layer-classes-be-singletons