controller默認是單例的,不要使用非靜態的成員變量,否則會發生數據邏輯混亂。正因為單例所以不是線程安全的。
驗證示例:
@Controller public class HelloController { private int num = 0; @GetMapping(value = "/testScope") @ResponseBody public void testScope() { System.out.println(++num); } @GetMapping(value = "/testScope2") @ResponseBody public void testScope2() { System.out.println(++num); } }
首先訪問 http://localhost:8081/testScope
,得到的是1
;
然后再訪問 http://localhost:8081/testScope2
,得到的是 2
。
得到的不同的值,這是線程不安全的。
給controller
增加作用多例 @Scope("prototype")
@Controller
@Scope("prototype") public class HelloController { private int num = 0; @GetMapping(value = "/testScope") @ResponseBody public void testScope() { System.out.println(++num); } @GetMapping(value = "/testScope2") @ResponseBody public void testScope2() { System.out.println(++num); } }
首先訪問 http://localhost:8081/testScope
,得到的是1
;
然后再訪問 http://localhost:8081/testScope2
,得到的是 2
。
單例是不安全的,會導致屬性重復使用。
解決方案
1、不要在controller中定義成員變量。
2、萬一必須要定義一個非靜態成員變量時候,則通過注解@Scope(“prototype”),將其設置為多例模式。
3、在Controller中使用ThreadLocal變量
文章來源:https://blog.csdn.net/riemann_/article/details/97698560