Spring IOC scope

来源:互联网 发布:狮王祛痘膏淘宝类目 编辑:程序博客网 时间:2024/05/19 16:29

1.The singleton scope

简单的描述为,每个容器只有一个实例。这个容器可以理解为Bean的factory。如下图所示(绿圈代表一个实例),所有用到accountDao的对象都是引用的同一个对象。Spring 默认的就是singleton模式。

<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"/>

singleton


2.The prototype scope

简单描述为,他会为每个请求创建一个新的对象。

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

prototype

但是spring并不管理的prototype实例的整个生命周期,即他只负责创建和初始化对象,并移交给它所需要的对象。所创建的实例需要client,也就是用实例的那方自行销毁,具体方法 用bean post-processor,此方法持有该实例的一个索引。

3.在singleton实例上注入prototype实例

在singleton实例上注入prototype实例,它的依赖关系是在对象初始化时实现的,也就是说在容器内进行初始化,然后送给客户端(也就是用对象那一方)。singleton实例是唯一的,prototype实例不是唯一的,如果你想频繁的在runtime时在singleton中更新替换prototype实例,那就需要用到“Method injection”。

4.Request scope

他会为每个HTTP request请求创建一个loginAction对象

<span style="font-family:FangSong_GB2312;font-size:18px;"><span style="font-size:18px;"><bean id="loginAction" class="com.foo.LoginAction" scope="request"/></span></span>

5.Session scope

同4,他会每个HTTP session分配一个独立实例

<span style="font-family:FangSong_GB2312;font-size:18px;"><span style="font-size:18px;"><bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/></span></span>
6.global session

global session 和标准的HTTP session类似,它只应用于给予portlat的web应用的上下文当中。portlet说明文档描述了global session是在各个portlets之间共享。

7.Application scope

<span style="font-family:FangSong_GB2312;font-size:18px;"><span style="font-size:18px;"><bean id="appPreferences" class="com.foo.AppPreferences" scope="application"/></span></span>
Application scope是在ServletContext级别的,他会为每个ServletContext分配一个唯一的实例。区别于singleton模式为每一个applicationContext分配一个唯一的实例,








0 0