java - 如果单例不好!为什么spring bean默认是单调的

标签 java spring

这个问题在这里已经有了答案:





Singleton design pattern vs Singleton beans in Spring container

(11 个回答)


5年前关闭。




What is so bad about singletons?

已经解释得很清楚了,单例设计模式违反了多个最佳实践。那为什么spring beans默认是单例的呢?这种设计不会间接导致同样的违规行为吗?

最佳答案

单例模式和 Spring 单例模式几乎没有共同之处。实际上唯一的可能是:

生产运行时只有一个实例

让我们从您链接到的答案中了解该模式的批评者:

They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.



使用 Spring,您正在做完全相反的事情。你只是说:“我需要其中之一,而不关心它来自哪里。”

They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.



再说一遍:Spring 正好相反:你编写一个普通的 pojo,然后在你的 Spring 配置中配置它应该有什么生命周期。

They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.



使用 Spring,没有什么能阻止您为每个测试使用不同的实例。

They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.



是的,它们可以在应用程序的整个生命周期中携带状态,但是由于您可以选择更改生命周期或测试中的实现(或应用程序的不同实例),因此测试彼此保持独立。

所有这些都不是 Spring 特有的,但可能适用于所有成熟的依赖注入(inject)框架,甚至当您选择手动执行时也是如此。

关于java - 如果单例不好!为什么spring bean默认是单调的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41503326/

相关文章:

java - 每次重新启动时 Eclipse 都会将 Java 编译器合规性级别重置为 1.7

java - 如何在 Spring Boot 应用程序中以 JSONObject 形式访问 MongoDB 文档

java - 如何模拟 Throwable 对象?

java - Camunda 在启动共享流程定义时设置租户 ID

java - 如何使用 eclipse 在 appEngine 上运行 google test-analytics 项目

java - 玩!根地址的框架路由通配符

java - 创建 Spring bean 时未知属性 accessExternalDTD

java - ListView 或 ScrollPane 滚动条不滚动

java - Spring aop : can't find referenced pointcut annotation

java - 如何重新初始化一个Spring Bean?