Controller 是單例還是多例?怎么保證并發(fā)的安全
閱讀本文大概需要 2 分鐘。
來自:網絡
package?com.riemann.springbootdemo.controller;
import?org.springframework.context.annotation.Scope;
import?org.springframework.stereotype.Controller;
import?org.springframework.web.bind.annotation.RequestMapping;
/**
?*?@author?riemann
?*?@date?2019/07/29?22:56
?*/
@Controller
public?class?ScopeTestController?{
????private?int?num?=?0;
????@RequestMapping("/testScope")
????public?void?testScope()?{
????????System.out.println(++num);
????}
????@RequestMapping("/testScope2")
????public?void?testScope2()?{
????????System.out.println(++num);
????}
}
package?com.riemann.springbootdemo.controller;
import?org.springframework.context.annotation.Scope;
import?org.springframework.stereotype.Controller;
import?org.springframework.web.bind.annotation.RequestMapping;
/**
?*?@author?riemann
?*?@date?2019/07/29?22:56
?*/
@Controller
@Scope("prototype")
public?class?ScopeTestController?{
????private?int?num?=?0;
????@RequestMapping("/testScope")
????public?void?testScope()?{
????????System.out.println(++num);
????}
????@RequestMapping("/testScope2")
????public?void?testScope2()?{
????????System.out.println(++num);
????}
}
解決方案
補充說明
singleton:單例模式,當spring創(chuàng)建applicationContext容器的時候,spring會欲初始化所有的該作用域實例,加上lazy-init就可以避免預處理;
prototype:原型模式,每次通過getBean獲取該bean就會新產生一個實例,創(chuàng)建后spring將不再對其管理;
(下面是在web項目下才用到的)
request:搞web的大家都應該明白request的域了吧,就是每次請求都新產生一個實例,和prototype不同就是創(chuàng)建后,接下來的管理,spring依然在監(jiān)聽;
session:每次會話,同上;
global session:全局的web域,類似于servlet中的application。
推薦閱讀:
微信掃描二維碼,關注我的公眾號????
朕已閱?

