开发者

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!


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.


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.


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).


Service layer should be Singleton, otherwise for every incoming request a new object will be created and these objects are heavy contains business logic and lots of line of code. They must be Singleton.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜