<bean id="loginAction" class="org.han.action.LoginAction" scope="singleton">
<property name="user" ref="user"></property>
</bean>
在spring2.0以前bean只有2種做用域即:singleton(單例)、non-singleton(也稱prototype), Spring2.0之後,增長了session、request、global session三種專用於Web應用程序上下文的Bean。所以,默認狀況下Spring2.0如今有五種類型的Bean。固然,Spring2.0對Bean的類型的設計進行了重構,並設計出靈活的Bean類型支持,理論上能夠有無數多種類型的Bean,用戶能夠根據本身的須要,增長新的Bean類型,知足實際應用需求。java
一、singleton和prototype做用域web
<bean id="date" class="java.util.Date" scope="singleton"></bean>
ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); Date d=context.getBean("date",Date.class); System.out.println(d); Thread.sleep(5000); d=context.getBean("date",Date.class); System.out.println(d);
上述示例中獲得的時間將是同樣的
修改一下:spring
<bean id="date" class="java.util.Date" scope="prototype"></bean>
當使用prorotype做爲做用域時,Bean會致使每次對該Bean的請求都建立一個Bean實例,因此對有狀態的Bean應該使用prorotype做用域,無狀態Bean則使用singleton做用域。還有就是Spring不能對一個prototype做用域 bean的整個生命週期負責,容器在初始化、配置、裝飾或者是裝配完一個prototype實例後,將它交給客戶端,隨後就對該prototype實例漠不關心了。無論何種做用域,容器都會調用全部對象的初始化生命週期回調方法,而對prototype而言,任何配置好的析構生命週期回調方法都將不會被調用。清除prototype做用域的對象並釋聽任何prototype bean所持有的昂貴資源,都是客戶端代碼的職責。(讓Spring容器釋放被singleton做用域bean佔用資源的一種可行方式是,經過使用bean的後置處理器,該處理器持有要被清除的bean的引用。)設計模式
<web-app> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> </web-app>
若是是Servlet2.4之前的web容器,那麼你要使用一個javax.servlet.Filter的實現:緩存
<filter> <filter-name>requestContextFilter</filter-name> <filter-class> org.springframework.web.filter.RequestContextFilter </filter-class> </filter> <filter-mapping> <filter-name>requestContextFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.一、request
request表示該針對每一次HTTP請求都會產生一個新的bean,同時該bean僅在當前HTTP request內有效。session
<bean id="loginAction" class="org.han.action.LoginAction" scope="request"/>
<bean id="loginAction" class="org.han.action.LoginAction" scope="session"/>
<bean id="loginAction" class="org.han.action.LoginAction" scope="globalSession"/></span>
在spring2.0中做用域是能夠任意擴展的,可是不能覆蓋singleton和prototype,spring的做用域由接口org.springframework.beans.factory.config.Scope來定義,自定義本身的做用域只要實現該接口便可app