Spring(八):Bean的作用域
Spring框架支持六个作用域,其中四个只有在Web中才能用到,在此我们只说明前两种作用域。
下面是所有的六种作用域:
Scope | Description |
---|---|
singleton |
(Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
prototype |
Scopes a single bean definition to any number of object instances. |
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 . |
session |
Scopes a single bean definition to the lifecycle of an HTTP . Only valid in the context of a web-aware Spring . |
application |
Scopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring . |
websocket |
Scopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring . |
这里我们对前两种singleton(单例)和prototype(原型进行学习)。
一、singleton
单例作用域是Spring框架的默认作用域。官方对它的说明是这样的:
仅管理单例 Bean 的一个共享实例,并且所有对 ID 或 ID 与该 Bean 定义匹配的 Bean 的请求都会导致 Spring 容器返回该特定 Bean 实例。
换句话说,当你定义一个bean定义并且它的范围是一个单例时,Spring IoC容器只创建由该bean定义定义的对象的一个实例。此单个实例存储在此类单例 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"/>