Java Spring服务是单例的吗? [英] Are Java Spring services evil as they are singleton?

查看:49
本文介绍了Java Spring服务是单例的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了许多有关网络和堆栈的讨论,这些讨论声称单例是邪恶的.喜欢: singletons的根本原因为什么Singleton被视为反模式?

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?

我阅读了诸如让代码变得复杂,重用和测试的痛苦"之类的注释.我使用的代码具有Spring Services,这些代码是无状态的单例,我看不出这些观点在这里的含义.

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?

推荐答案

您已经将Spring的单例(这是一件普遍的事情)与 Singleton设计模式混淆了,该模式受您所讨论的问题的困扰参考资料.

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.

Singleton模式假定存在一个引用单例对象的 static 全局变量.通常还假定有很多样板代码用于管理单例的生命周期(例如,延迟初始化).

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既不使您实现Singleton模式,也不在内部使用它.Spring单例以声明方式创建,并连接到完整的对象图中,包括循环依赖项的解析.

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.

这篇关于Java Spring服务是单例的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆