Spring框架参考手册(4.2.6版本)翻译——第三部分 核心技术 6.5.1 单例(singleton)作用域

 6.5.1 单例(singleton)作用域

定义为单例作用域的Bean,在Spring容器中只会存在一个实例,这个实例是共享的,所有匹配这个Bean的请求,Spring容器返回此共享的实例。
换句话说,当您定义bean定义并将其作用域设置为singleton时,Spring IoC容器只会创建该bean定义对象的一个实例。 此单个实例存储在此类单例bean的缓存中,并且该命名Bean的所有后续请求和引用都将返回此缓存对象。


Spring的单例bean的概念不同于Gang of Four(GoF)模式书中定义的Singleton模式。GoF Singleton对对象的作用域进行硬编码,使得每个ClassLoader创建一个且只有一个特定类的实例。Spring单例的作用域最好描述为“单容器,单个bean”。 这意味着如果在单个Spring容器中为特定类定义一个bean,则Spring容器将创建该bean定义所定义的类的一个且仅一个实例。在Spring中,单例作用域为默认作用域。要将bean定义为XML中的单例,您可以编写,例如:

<bean id="accountService" class="com.foo.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>

原文地址:https://www.cnblogs.com/springmorning/p/10347519.html