7.5.1 The singleton scope

Only one shared instance of a singleton bean is managed, and all requests for beans with an id or ids matching that bean definition result in that one specific bean instance being returned by the Spring container.

仅有一个共享实例的单例bean被管理着,所有通过id或ids去匹配beans的请求,Spring容器只会返回一个指定的bean实例.

To put it another way, when you define a bean definition and it is scoped as a singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.

换一种说法,当你将一个bean定义成单例bean的时候,Spring IoC容器会通过bean定义创建一个对象定义实例.这个单个的实例会存储在例如单例beans的缓存中,之后所有的请求和引用都会返回缓存的对象.

singleton

Spring’s concept of a singleton bean differs from the Singleton pattern as defined in the Gang of Four (GoF) patterns book. The GoF Singleton hard-codes the scope of an object such that one and only one instance of a particular class is created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container creates one and only one instance of the class defined by that bean definition. The singleton scope is the default scope in Spring. To define a bean as a singleton in XML, you would write, for example:

Spring中的单例bean的概念不同于在GoF模式书中的单例设计模式.GoF单例硬编码的对象域是每一次类加载的时候创建这个类仅有的一个实例.Spring单例域的最好描述为一个容器一个bean.这句话意味着如果你在Spring容器中定义了一个单例bean,然后Spring容器仅会创建一个实例.单例域是Spring默认的域.在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"/>

猜你喜欢

转载自blog.csdn.net/weixin_41648566/article/details/81109271