bean的作用域

          Posted on 2009-07-09 16:37 胡娟 閱讀(718) 評論(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 © 胡娟

          主站蜘蛛池模板: 苗栗县| 韩城市| 贡山| 江北区| 吴忠市| 麻栗坡县| 花垣县| 怀远县| 延安市| 新泰市| 商洛市| 嵊州市| 韶关市| 和政县| 米泉市| 海门市| 克山县| 宜昌市| 石阡县| 平武县| 蓬溪县| 宁津县| 广州市| 樟树市| 扎兰屯市| 迁西县| 久治县| 晋宁县| 荥阳市| 三门县| 竹北市| 信宜市| 嘉定区| 华宁县| 根河市| 安国市| 定远县| 道孚县| 宜兰县| 克什克腾旗| 西青区|