使用SpringMVC的時候,如果想要在Controller中定義一個全局變量,並且實現在不同用戶訪問程序的時候,所得到的全局變量不一樣的(線程安全的),這個時候就可以用Spring的注解@Scope來實現:\
@Controller
//把這個bean 的范圍設置成session,表示這bean是會話級別的,
@Scope("session")
public class XxxController{
private List<String> list ;
//PostConstruct當bean加載完之后,就會執行init方法,並且將list實例化;
@PostConstruct
public void init(){
list = new ArrayList<String>();
}
}
當我們首次訪問這個Controller的時候,他會根據判斷這個會話是不是處於同一個session中,如果是一個新的,容器會執行init方法,如果一樣就不會。
下面簡單說下@Scope這個注解的理解
spring中bean的scope屬性,有如下5種類型:
singleton 表示在spring容器中的單例,通過spring容器獲得該bean時總是返回唯一的實例
prototype表示每次獲得bean都會生成一個新的對象
request表示在一次http請求內有效(只適用於web應用)
session表示在一個用戶會話內有效(只適用於web應用)
globalSession表示在全局會話內有效(只適用於web應用)
在多數情況,我們只會使用singleton和prototype兩種scope,如果在spring配置文件內未指定scope屬性,默認為singleton。
單例的原因有二:
1、為了性能。
2、不需要多例。
--》單例不用每次都new,當然快了。
--》不需要實例會讓很多人迷惑,因為spring mvc官方也沒明確說不可以多例。
我這里說不需要的原因是看開發者怎么用了,如果你給controller中定義很多的屬性,那么單例肯定會出現競爭訪問了。
package com.lavasoft.demo.web.controller.lsh.ch5;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by Administrator on 14-4-9.
*
* @author leizhimin 14-4-9 上午10:55
*/
@Controller
@RequestMapping("/demo/lsh/ch5")
@Scope("prototype")
public class MultViewController {
private static int st = 0; //靜態的
private int index = 0; //非靜態
@RequestMapping("/test")
public String test() {
System.out.println(st++ + " | " + index++);
return "/lsh/ch5/test";
}
}
單例的:
0 | 0
1 | 1
2 | 2
3 | 3
4 | 4
改為多例的:
0 | 0
1 | 0
2 | 0
3 | 0
4 | 0
最佳實踐:定義一個非靜態成員變量時候,則通過注解@Scope("prototype"),將其設置為多例模式。