Are Java Spring services evil as they are singleton? [closed]

≯℡__Kan透↙ 提交于 2020-03-03 04:43:11

问题


I have read a number of discussions on web and stack which claim singletons to be evil. Like: root-cause-of-singletons and Why is Singleton considered an anti-pattern?

I read comments like "singletons make code complex, pain to reuse and test". I work with code that has Spring Services which are stateless singletons and I can't see how those points hold here.

Do such services also qualify as bad practices and why? Or all the debate is on statefull singletons only?


回答1:


You have confused Spring's singletons (a universally good thing) with the Singleton design pattern, which suffers from the issues talked about in your referenced material.

The Singleton pattern assumes the existence of a static global variable referring to the singleton object. It often also assumes a lot of boilerplate code used to manage the singleton's lifecycle (lazily initialize it, for example).

Spring neither makes you implement the Singleton pattern, nor does it use it internally. Spring singletons are created declaratively and wired together into complete object graphs, including the resolution of circular dependencies.




回答2:


(Comment as answer for readability.)

Singletons aren't intrinsically evil, they're just easy to mis-use.

If you're not managing the singleton-ness of the object there's even less of an issue.

I'll disagree with the others regarding singletons with state; while it can be done wrong, there are many singleton patterns with state that work just fine, e.g., a pool.




回答3:


A Spring Singleton is evil if it is stateful. A stateless singleton is fine :

  • no field,
  • or stateless fields (for example a datasource), initialized at startup.


来源:https://stackoverflow.com/questions/26719981/are-java-spring-services-evil-as-they-are-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!