bean的作用域

          Posted on 2009-07-09 16:37 胡娟 閱讀(719) 評論(0)  編輯  收藏 所屬分類: JAVA

          Singleton作用域

          當一個bean的作用域為singleton,那么Spring Ioc容器中只會存在一個共享的bean實例,并且所有對bean的請求,只要id與該bean定義相匹配,則只會返回bean的同一實例。也就是說,當把一個bean定義設置為singleton作用域時,Spring IoC容器只會創建該bean定義的唯一實例。這個單一實例會被存儲到單例緩存中,并且所有針對該bean的后續請求和引用都將返回被緩存的對象實例。假如在單個Spring容器內定義了某個指定classbean,那么Spring容器將會創建一個且僅有一個由該bean定義知道的類實例。Singleton作用域是Spring中的缺省作用域。要在XML中將bean定義成singleton。其配置:

          <bean id="userDaoImpl" class="com.hujuan.dao.impl.UserDaoImpl" scope="singleton"></bean>

          Prototype作用域

          Prototype作用域的bean會導致在每次對該bean請求(將其注入到另一個bean中,或者以程序的方式調用容器的getBean()方法)時都會創建一個新的bean實例,根據經驗,對有狀態的bean應該使用prototype作用域,而對無狀態的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容器會根據userDaoImpl bean定義創建一個全新的UserDaoImpl bean實例,且該userDaoImpl bean實例僅在當前HTTP request內有效,因此可以根據需要放心的更改所建實例的內部狀態,而其他請求中根據userDaoImpl bean定義創建的實例,將不會看到這些特定于某個請求的狀態變化。當處理結束,request作用域的bean實例將銷毀。

          Session作用域

          <bean id="userDaoImpl" class="com.hujuan.dao.impl.UserDaoImpl" scope="session"></bean>

          針對某個HTTP sessionSpring容器會根據userDaoImpl bean定義創建一個全新的userDaoImpl bean實例,且該userDaoImpl bean僅在當前HTTP Session內有效。與request作用域一樣,你可以根據需要放心的更改所創建實例的內部狀態,而別的HTTP Session中根據userDaoImpl創建的實例,將不會看到這些特定于某個HTTP Session的狀態變化。當HTTP Sessison最終被廢棄的時候,在該HTTP Session作用域內的bean也會被廢棄掉。

          global session作用域

          <bean id="userDaoImpl" class="com.hujuan.dao.impl.UserDaoImpl" scope="globalSession"/>

          global session作用域類似于標準的HTTP Session作用域,不過僅僅在基于portletweb應用中才有意義。Portlet規范定義了全局Session的概念,它被所有構成某個portlet web應用的各種不同的portlet所共享。在global session作用域中定義的bean被限定于全局portlet Session的生命周期范圍內。



          posts - 28, comments - 5, trackbacks - 0, articles - 1

          Copyright © 胡娟

          主站蜘蛛池模板: 揭东县| 宁武县| 晋城| 谢通门县| 怀安县| 兴安县| 嘉定区| 邵东县| 阳曲县| 绿春县| 台北市| 武平县| 澄江县| 霍城县| 元朗区| 无为县| 安丘市| 博罗县| 常德市| 东阿县| 栖霞市| 涟水县| 太保市| 新和县| 都匀市| 沅江市| 开化县| 古交市| 綦江县| 资兴市| 肃宁县| 南岸区| 江都市| 双峰县| 崇文区| 阜宁县| 吉水县| 高州市| 安顺市| 镇安县| 巴林右旗|