轉:spring mvc 設置@Scope("prototype")

spring中bean的scope屬性,有以下5種類型:web

singleton 表示在spring容器中的單例,經過spring容器得到該bean時老是返回惟一的實例
prototype表示每次得到bean都會生成一個新的對象
request表示在一次http請求內有效(只適用於web應用)
session表示在一個用戶會話內有效(只適用於web應用)
globalSession表示在全局會話內有效(只適用於web應用)
在多數狀況,咱們只會使用singleton和prototype兩種scope,若是在spring配置文件內未指定scope屬性,默認爲singleton。spring

單例的緣由有二:
一、爲了性能。session

二、不須要多例。mvc

 

一、單例不用每次都new,固然快了。app

二、不須要實例會讓不少人迷惑,由於spring mvc官方也沒明確說不能夠多例。性能

  我這裏說不須要的緣由是看開發者怎麼用了,若是你給controller中定義不少的屬性,那麼單例確定會出現競爭訪問了。ui

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";
    }
}spa

單例的:.net

0 | 0prototype

1 | 1

2 | 2

3 | 3

4 | 4

 

改成多例的:

0 | 0

1 | 0

2 | 0

3 | 0

4 | 0

 

最佳實踐:定義一個非靜態成員變量時候,則經過註解@Scope("prototype"),將其設置爲多例模式。

相關文章
相關標籤/搜索