Spring 的 Controller 是單例還是多例?怎么保證并發(fā)的安全

我們經(jīng)常說單例還是多例,那么究竟他們不同的根源在哪?或者說我們應(yīng)該從哪一方面具體的去理解了,至于這個問題,今天來分享一波
答案:
controller默認(rèn)是單例的,不要使用非靜態(tài)的成員變量,否則會發(fā)生數(shù)據(jù)邏輯混亂。正因為單例所以不是線程安全的。
我們下面來簡單的驗證下:
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 2020/01/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;然后我們再訪問 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 2020/01/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;
然后我們再訪問 http://localhost:8080/testScope2,得到的答案還是1。
相信大家不難發(fā)現(xiàn) :
單例是不安全的,會導(dǎo)致屬性重復(fù)使用
解決方案
1、 不要在controller中定義成員變量。
2、 萬一必須要定義一個非靜態(tài)成員變量時候,則通過注解@Scope(“prototype”),將其設(shè)置為多例模式。
3、 在Controller中使用ThreadLocal變量
補充說明
2、 prototype:原型模式,每次通過getBean獲取該bean就會新產(chǎn)生一個實例,創(chuàng)建后spring將不再對其管理;
5、 session:每次會話,同上;

往 期 推 薦
1、Intellij IDEA這樣 配置注釋模板,讓你瞬間高出一個逼格! 2、基于SpringBoot的迷你商城系統(tǒng),附源碼! 3、最牛逼的 Java 日志框架,性能無敵,橫掃所有對手! 4、把Redis當(dāng)作隊列來用,真的合適嗎? 5、驚呆了,Spring Boot居然這么耗內(nèi)存!你知道嗎? 6、全網(wǎng)最全 Java 日志框架適配方案!還有誰不會? 7、Spring中毒太深,離開Spring我居然連最基本的接口都不會寫了

點分享

點收藏

點點贊

點在看
評論
圖片
表情

