Posted on 2009-07-09 16:37
胡娟 閱讀(713)
評論(0) 編輯 收藏 所屬分類:
JAVA
Singleton作用域
當一個bean的作用域為singleton,那么Spring Ioc容器中只會存在一個共享的bean實例,并且所有對bean的請求,只要id與該bean定義相匹配,則只會返回bean的同一實例。也就是說,當把一個bean定義設置為singleton作用域時,Spring IoC容器只會創(chuàng)建該bean定義的唯一實例。這個單一實例會被存儲到單例緩存中,并且所有針對該bean的后續(xù)請求和引用都將返回被緩存的對象實例。假如在單個Spring容器內定義了某個指定class的bean,那么Spring容器將會創(chuàng)建一個且僅有一個由該bean定義知道的類實例。Singleton作用域是Spring中的缺省作用域。要在XML中將bean定義成singleton。其配置:
<bean id="userDaoImpl" class="com.hujuan.dao.impl.UserDaoImpl" scope="singleton"></bean>
Prototype作用域
Prototype作用域的bean會導致在每次對該bean請求(將其注入到另一個bean中,或者以程序的方式調用容器的getBean()方法)時都會創(chuàng)建一個新的bean實例,根據(jù)經(jīng)驗,對有狀態(tài)的bean應該使用prototype作用域,而對無狀態(tài)的bean則應該使用singleton作用域,要在XML中將bean定義成prototype,其配置:
<bean id="userDaoImpl" class="com.hujuan.dao.impl.UserDaoImpl" scope="prototype"></bean>
Request
作用域
<bean id="userDaoImpl" class="com.hujuan.dao.impl.UserDaoImpl" scope="request"></bean>
針對每次Http請求,Spring容器會根據(jù)userDaoImpl
bean定義創(chuàng)建一個全新的UserDaoImpl bean實例,且該userDaoImpl bean實例僅在當前HTTP request內有效,因此可以根據(jù)需要放心的更改所建實例的內部狀態(tài),而其他請求中根據(jù)userDaoImpl bean定義創(chuàng)建的實例,將不會看到這些特定于某個請求的狀態(tài)變化。當處理結束,request作用域的bean實例將銷毀。
Session作用域
<bean id="userDaoImpl" class="com.hujuan.dao.impl.UserDaoImpl" scope="session"></bean>
針對某個HTTP session,Spring容器會根據(jù)userDaoImpl bean定義創(chuàng)建一個全新的userDaoImpl bean實例,且該userDaoImpl bean僅在當前HTTP Session內有效。與request作用域一樣,你可以根據(jù)需要放心的更改所創(chuàng)建實例的內部狀態(tài),而別的HTTP
Session中根據(jù)userDaoImpl創(chuàng)建的實例,將不會看到這些特定于某個HTTP Session的狀態(tài)變化。當HTTP Sessison最終被廢棄的時候,在該HTTP Session作用域內的bean也會被廢棄掉。
global
session作用域
<bean id="userDaoImpl" class="com.hujuan.dao.impl.UserDaoImpl" scope="globalSession"/>
global
session作用域類似于標準的HTTP Session作用域,不過僅僅在基于portlet的web應用中才有意義。Portlet規(guī)范定義了全局Session的概念,它被所有構成某個portlet web應用的各種不同的portlet所共享。在global session作用域中定義的bean被限定于全局portlet Session的生命周期范圍內。