Spring框架學習與實踐(四)

Spring 中 Bean 的作用域演練

Spring 中 Bean 有5種作用域,後面會詳細介紹 singleton 和 prototype 這兩種最常用的作用域。

作用域的種類

Spring 容器在初始化一個 Bean 的實例時,同時會指定該實例的作用域。Spring3 爲 Bean 定義了五種作用域,具體如下:

1, singleton

單例模式,使用 singleton 定義的 Bean 在 Spring 容器中只有一個實例,這也是 Bean 默認的作用域

2, prototype

原型模式,每次通過 Spring 容器獲取 prototype 定義的 Bean 時,容器都將創建一個新的 Bean 實例

3, request

在一次 HTTP 請求中,容器會返回該 Bean 的同一個實例。而對不同的 HTTP 請求,會返回不同的實例,該作用域僅在當前 HTTP Request 內有效

4, session

在一次 HTTP Session 中,容器會返回該 Bean 的同一個實例。而對不同的 HTTP 請求,會返回不同的實例,該作用域僅在當前 HTTP Session 內有效

5, global Session

在一個全局的 HTTP Session 中,容器會返回該 Bean 的同一個實例。該作用域僅在使用 portlet context 時有效

在上述五種作用域中,singleton 和 prototype 是最常用的兩種,接下來將對這兩種作用域進行詳細講解。

singleton 的作用域

singleton 是 Spring 容器默認的作用域,當一個 Bean 的作用域爲 singleton 時,Spring 容器中只會存在一個共享的 Bean 實例,並且所有對 Bean 的請求,只要 id 與該 Bean 定義相匹配,就只會返回 Bean 的同一個實例。通常情況下,這種單例模式對於無會話狀態的 Bean(如 DAO 層、Service 層)來說,是最理想的選擇。

在 Spring 配置文件中,可以使用 <bean> 元素的 scope 屬性,將 Bean 的作用域定義成 singleton,其配置方式如下所示:

<bean id="person" class="com.mengma.scope.Person" scope="singleton"/>

在項目的 src 目錄下創建一個名爲 com.mengma.scope 的包,在該包下創建 Person 類,類中不需要添加任何成員,然後創建 Spring 的配置文件 applicationContext.xml,將上述 Bean 的定義方式寫入配置文件中,最後創建一個名爲 PersonTest 的測試類,編輯後如下所示:

package com.mengma.scope;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonTest {
	@Test
	public void test() {
		// 定義Spring配置文件路徑
		String xmlPath = "com/mengma/scope/applicationContext.xml";
		// 初始化Spring容器,加載配置文件,並對bean進行實例化
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		// 輸出獲得示例
		System.out.println(applicationContext.getBean("person"));
		System.out.println(applicationContext.getBean("person"));
	}

}

使用 JUnit 測試運行PersonTest,運行成功後,控制檯的輸出結果如圖:

從上圖可以看到,兩次輸出的結果相同,這說明 Spring 容器只創建了一個 Person 類的實例。由於 Spring 容器默認作用域是 singleton,如果不設置 scope="singleton",則其輸出結果也將是一個實例。 

prototype 的作用域

使用 prototype 作用域的 Bean 會在每次請求該 Bean 時都會創建一個新的 Bean 實例。因此對需要保持會話狀態的 Bean(如  Struts2 的 Action 類)應該使用 prototype 作用域。

在 Spring 配置文件中,要將 Bean 定義爲 prototype 作用域,只需將 <bean> 元素的 scope 屬性值定義成 prototype,其示例代碼如下所示:

<bean id="person" class="com.mengma.scope.Person" scope="prototype"/>

將 "singleton的作用域" 部分中的配置文件更改成上述代碼形式後,再次運行PersonTest,控制檯的輸出結果如圖所示:

 從上圖的輸出結果中可以看到,兩次輸出的結果並不相同,這說明在 prototype 作用域下,Spring 容器創建了兩個不同的 Person 實例。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章