spring-Bean Scopes Bean作用域

1.5. Bean Scopes Bean作用域

When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object instances from a single recipe.

当您创建一个bean定义时,您将创建一个用于创建由该bean定义定义的类的实际实例的方法。bean定义是一个配方的想法很重要,因为这意味着,与类一样,您可以从单个配方创建多个对象实例。

You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition but also control the scope of the objects created from a particular bean definition. This approach is powerful and flexible, because you can choose the scope of the objects you create through configuration instead of having to bake in the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes. The Spring Framework supports six scopes, four of which are available only if you use a web-aware ApplicationContext. You can also create a custom scope.

您不仅可以控制要插入到从特定bean定义创建的对象中的各种依赖关系(dependencies )和配置值( configuration values),还可以控制从特定bean定义创建的对象的scope。这种方法功能强大且灵活,因为您可以选择通过配置创建的对象的scope,而不必在Java类级别烘焙对象的scope。可以将bean定义为部署在多个作用域中的一个。Spring框架支持6个作用域,其中4个作用域仅在使用支持web的ApplicationContext时可用。也可以创建自定义scope

The following table describes the supported scopes:

Scope Description
singleton (Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
单列 (默认)将单个bean定义的范围限定为每个springioc容器的单个对象实例。
prototype Scopes a single bean definition to any number of object instances.
原型 将单个bean定义的范围限定为任意数量的对象实例。
request Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
将单个bean定义限定为单个HTTP请求的生命周期。也就是说,每个HTTP请求都有一个在单个bean定义后面创建的bean实例。仅在支持web的Spring应用程序上下文(ApplicationContext)中有效。(是单列的,bean实例只有一个)
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
将单个bean定义限定为HTTP会话的生命周期。仅在支持web的Spring应用程序上下文(ApplicationContext)中有效。
application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
将单个bean定义限定为ServletContext的生命周期。仅在支持web的Spring应用程序上下文中有效。
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
将单个bean定义限定为WebSocket的生命周期。仅在支持web的SpringApplicationContext中有效。

As of Spring 3.0, a thread scope is available but is not registered by default. For more information, see the documentation for SimpleThreadScope. For instructions on how to register this or any other custom scope, see Using a Custom Scope.

从spring3.0开始,线程范围是可用的,但默认情况下不注册。有关更多信息,请参阅SimpleThreadScope的文档。有关如何注册此自定义范围或任何其他自定义范围的说明,请参阅使用自定义范围(Using a Custom Scope)

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只有一个共享实例是被管理的,所有对具有与该bean定义相匹配的ID的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时,springioc容器将创建由该bean定义定义的对象的一个实例。这个单个实例存储在这样的单例bean的缓存中,并且该命名bean的所有后续请求和引用都返回缓存的对象。下图显示了singleton作用域的工作方式:

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的singleton bean概念不同于gang of four(GoF)patterns一书中定义的singleton模式。GoF singleton硬编码对象的范围,每个类加载器只创建一个特定类的实例。spring singleton的范围最好描述为每个容器和每个bean(bean在容器中是唯一的就行)。这意味着,如果您在单个Spring容器中为特定类定义一个bean,那么Spring容器将创建一个且仅一个由该bean定义定义的类的实例。singleton作用域是Spring中的默认作用域。要在XML中将bean定义为单例,可以定义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"/>

1.5.2. The Prototype Scope (原型范围)

The non-singleton prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made. That is, the bean is injected into another bean or you request it through a getBean() method call on the container. As a rule, you should use the prototype scope for all stateful beans and the singleton scope for stateless beans.

bean部署的非单例原型范围导致每次对特定bean发出请求时都会创建一个新的bean实例。也就是说,该bean被注入到另一个bean中,或者您通过对容器的getBean()方法调用来请求它。通常,您应该为所有有状态bean使用prototype范围,而为无状态bean使用singleton范围。

The following diagram illustrates the Spring prototype scope:

prototype

(A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state. It was easier for us to reuse the core of the singleton diagram.)

(数据访问对象(DAO)通常不配置为原型,因为典型的DAO不具有任何会话状态。我们更容易重用singleton图的核心。)

The following example defines a bean as a prototype in XML:

以下示例将bean定义为XML中的原型:

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean. The container instantiates, configures, and otherwise assembles a prototype object and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype beans hold. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.

与其他作用域不同,Spring不管理原型bean的完整生命周期。容器实例化、配置和组装一个原型对象并将其交给客户机,而不需要进一步记录该原型实例。因此,尽管初始化生命周期回调方法在所有对象上都被调用,而不管范围如何,对于原型,配置的销毁生命周期回调不会被调用。客户机代码必须清理原型范围内的对象,并释放原型bean所持有的昂贵资源。为了让Spring容器释放原型作用域bean所包含的资源,请尝试使用一个自定义bean后处理程序,它保存了对需要清理的bean的引用。

In some respects, the Spring container’s role in regard to a prototype-scoped bean is a replacement for the Java new operator. All lifecycle management past that point must be handled by the client. (For details on the lifecycle of a bean in the Spring container, see Lifecycle Callbacks.)

在某些方面,Spring容器在原型范围bean 中的角色是java new操作符的替代品。超过该点的所有生命周期管理都必须由客户端处理。(有关Spring容器中bean生命周期的详细信息,请参阅生命周期回调)

下一节:Singleton Beans with Prototype-bean Dependencies
具有原型bean依赖关系的单例bean

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,386评论 6 479
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,939评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,851评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,953评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,971评论 5 369
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,784评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,126评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,765评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,148评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,744评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,858评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,479评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,080评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,053评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,278评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,245评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,590评论 2 343

推荐阅读更多精彩内容