Spring Framework Documentation (5.3.10)
Core | IoC Container, Events, Resources, i18n, Validation, Data Binding, Type Conversion, SpEL, AOP. |
1. The IoC Container
1.1. Introduction to the Spring IoC Container and Beans(Spring IoC容器和bean简介)
1.2. Container Overview (容器概览)
1.5.1. The Singleton Scope (单例作用域)
1.5.2. The Prototype Scope(Prototype作用域)
1.5.3. Singleton Beans with Prototype-bean Dependencies(单例和原型Bean的依赖)
1.5.4. Request, Session, Application, and WebSocket Scopes
1.5.4.1. Initial Web Configuration (初始化Web配置)
1.5.4.4. Application Scope(应用作用域)
1.5.4.5. Scoped Beans as Dependencies (具有作用域的bean作为依赖项)
1.5.4.5.1 Choosing the Type of Proxy to Create(选择待创建代理的类型)
1.5.5.1. Creating a Custom Scope(创建自定义作用域)
1.5.5.2. Using a Custom Scope (使用自定义作用域)
更多章节内容,请点击查看: Core Technologies
1.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 that match that bean definition result in that one specific bean instance being returned by the Spring container.
只管理一个单例bean的一个共享实例,对具有ID或ID与bean定义匹配的bean的所有请求都会导致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. The following image shows how the singleton scope works:
换句话说,当您定义一个bean定义并将其作用域限定为单例(singleton)时,Spring IoC容器只创建该bean定义所定义对象的一个实例。这个实例存储在此种单例bean的一个缓存中,该具名bean的所有后续请求和引用都返回该缓存对象。下图展示了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 being per-container and per-bean. This means that, if you define one bean for a particular class in a single Spring container, 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 can define a bean as shown in the following example:
Spring的单例bean概念不同于*(GangofFour,GoF)模式书中定义的单例模式(singleton pattern)。GoF的单例硬编码了对象的作用域,这样每个类加载器(per ClassLoader)只创建一个特定类的实例。Spring单例的作用域最好描述为按容器(per-container)和按bean(per-bean)。这意味着,如果在单个Spring容器中为特定类定义一个bean,Spring容器将创建该bean定义的类的一个且只有一个实例。单例作用域是Spring中的默认作用域。要将bean定义为XML中的单例,可以如下例所示定义bean:
<bean id="accountService" class="com.something.DefaultAccountService"/>
<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>