Spring框架功能強大,其中一個經常使用的功能是使用IOC容器來管理Bean,在建立Bean的過程當中,主要有5中做用域,下面就來介紹一下每個做用域的特色和做用。html
一、Singleton:設置爲該模式的Bean,容器初始化時就建立一個Bean實例,並且該實例只存在一份。測試以下:java
建立SingleScope類: web
public class SingleScope { //建立空構造函數,用於測試IOC容器初始化時就建立該實例bean public SingleScope(){ System.out.println("Constructor go ---->"); } }
配置spring的配置文件ApplicationContext-scope.xml: spring
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd "> <!--配置bean,設置爲singleton模式--> <bean id="singleScope" class="com.wpb.scope.SingleScope" scope="singleton"/> </beans>
建立測試類: 設計模式
public class ScopeTest { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext-scope.xml"); SingleScope singleScope= (SingleScope) context.getBean("singleScope"); SingleScope singleScope1= (SingleScope) context.getBean("singleScope"); System.out.println(singleScope==singleScope1); } }
結果以下:session
須要注意的是:spring中bean的singleton模式與設計模式中的單例模式是兩個不一樣的概念,他們是有相同的特色,只實例一次。可是設計模式中的單例模式指的是ClassLoader加載該類時,只實例化一次。而bean的singleton模式指的是Spring IOC容器中只存在一份該bean。框架
二、Prototype:能夠存在多個bean實例,容器初始化時不會建立bean實例,使用時纔會建立。來看一下測試代碼:函數
建立PrototypeScope類: 測試
/** * Created by 王朋波 on 16/07/2017. */ public class PrototypeScope { public PrototypeScope(){ System.out.println("PrototypeScope constructor go --->"); } }
在spring的配置文件中添加以下配置: spa
<!--配置bean,設置爲Prototype模式 --> <bean id="prototypeScope" class="com.wpb.scope.PrototypeScope" scope="prototype"/>
測試代碼:
//當使用bean時,才建立實例。執行完下述獲取實例語句,PrototypeScope中的構造函數纔會執行 PrototypeScope prototypeScope= (PrototypeScope) context.getBean("prototypeScope"); PrototypeScope prototypeScope1= (PrototypeScope) context.getBean("prototypeScope"); System.out.println(prototypeScope==prototypeScope1);
運行結果:
注意的地方:Prototype bean被spring容器配置、裝載、實例化以後,其生命週期將由本身負責,也就是spring容器再也不管理它的生命週期,交給了客戶端進行管理。
比較經常使用的是singleton和Prototype,下面三種不經常使用,簡單瞭解一下基本概念和配置方式。
三、request:對於每次HTTP請求,使用request定義的Bean都將產生一個新實例,即每次HTTP請求將會產生不一樣的Bean實例。僅在基於web的Spring ApplicationContext情形下有效。
四、session:對於每次HTTP Session,使用session定義的Bean豆漿產生一個新實例。僅在基於web的Spring ApplicationContext情形下有效。
五、每一個全局的HTTP Session,使用session定義的Bean都將產生一個新實例。典型狀況下,僅在使用portlet context的時候有效。僅在基於web的Spring ApplicationContext情形下有效。
上述三種方式除了配置spring的配置文件以外,還須要在web.xml文件增長一個監聽設置,以下:
<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>
小結:
bean的做用域中,須要重點掌握Singleton和Prototype兩種方式,另外還須要與Struts2中配置Action時,也有這兩種模式做對比,明白各自的含義以及默認使用。