springmvc控制器controller單例問題

springmvc controller默認的是單例singleton的,具體能夠查看註解scope能夠一目瞭然。spring

單例的緣由有二:安全

一、爲了性能。mvc

二、不須要多例。app

 

一、這個不用廢話了,單例不用每次都new,固然快了。性能

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

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

  所以,只要controller中不定義屬性,那麼單例徹底是安全的。下面給個例子說明下:線程

@Controller
@RequestMapping("/demo")
public class MultViewController { private static int st = 0; //靜態的 private int index = 0; //非靜態 @RequestMapping("/test") public void test() { System.out.println(st++ + " | " + index++); } }

默認單例的,隨着請求次數的增長:code

0 | 0blog

1 | 1

2 | 2

3 | 3

4 | 4

...

controller增長註解:

@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)

此時,不管多少次請求,結果爲:

0 | 0

1 | 0

2 | 0

3 | 0

4 | 0

...

從以上很容易看出,單例是線程不安全的,會致使屬性的重複性利用。

 

最佳實踐:

一、不要在controller中定義成員變量。

二、萬一必需要定義一個非靜態成員變量時候,則經過註解@Scope("prototype"),將其設置爲多例模式

 

轉載自 http://lavasoft.blog.51cto.com/62575/1394669

相關文章
相關標籤/搜索