轉:【Spring MVC Controller單例陷阱】

來源:互聯網
上載者:User

標籤:

http://lavasoft.blog.51cto.com/62575/1394669/

Spring MVC Controller預設是單例的:


單例的原因有二:
1、為了效能。
2、不需要多例。


1、這個不用廢話了,單例不用每次都new,當然快了。
2、不需要執行個體會讓很多人迷惑,因為spring mvc官方也沒明確說不可以多例。
我這裡說不需要的原因是看開發人員怎麼用了,如果你給controller中定義很多的屬性,那麼單例肯定會出現競爭訪問了。
因此,只要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("/show")
public String toShow(ModelMap model) {
User user = new User();
user.setUserName("testuname");
user.setAge("23");
model.put("user", user);
return "/lsh/ch5/show";
}
@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


從此可見,單例是不安全的,會導致屬性重複使用。


最佳實務:
1、不要在controller中定義成員變數。
2、萬一必須要定義一個非靜態成員變數時候,則通過註解@Scope("prototype"),將其設定為多例模式

轉:【Spring MVC Controller單例陷阱】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.