Spring的 Controller是單例還是多例?怎么保證并發(fā)安全
點(diǎn)擊上方 好好學(xué)java ,選擇 星標(biāo) 公眾號(hào)
重磅資訊,干貨,第一時(shí)間送達(dá) 今日推薦:寫博客能月入 10K?
個(gè)人原創(chuàng)100W +訪問量博客:點(diǎn)擊前往,查看更多
答 案
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);
}
}
http://localhost:8080/testScope,得到的答案是1;然后我們?cè)僭L問 http://localhost:8080/testScope2,得到的答案是 2。controller增加作用多例 @Scope("prototype")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);
}
}
http://localhost:8080/testScope,得到的答案是1;然后我們?cè)僭L問 http://localhost:8080/testScope2,得到的答案還是 1。解決方案
補(bǔ)充說明
singleton: 單例模式,當(dāng)spring創(chuàng)建applicationContext容器的時(shí)候,spring會(huì)欲初始化所有的該作用域?qū)嵗由蟣azy-init就可以避免預(yù)處理;
prototype:原型模式,每次通過getBean獲取該bean就會(huì)新產(chǎn)生一個(gè)實(shí)例,創(chuàng)建后spring將不再對(duì)其管理;
(下面是在web項(xiàng)目下才用到的)
request:搞web的大家都應(yīng)該明白request的域了吧,就是每次請(qǐng)求都新產(chǎn)生一個(gè)實(shí)例,和prototype不同就是創(chuàng)建后,接下來的管理,spring依然在監(jiān)聽;
session: 每次會(huì)話,同上;
global session: 全局的web域,類似于servlet中的application。
更多項(xiàng)目源碼
評(píng)論
圖片
表情
