Spring的Controller是單例還是多例?怎么保證并發(fā)的安全
閱讀本文大概需要 2 分鐘。
controller默認(rèn)是單例的,不要使用非靜態(tài)的成員變量,否則會(huì)發(fā)生數(shù)據(jù)邏輯混亂。正因?yà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*/public class ScopeTestController {private int num = 0;public void testScope() {System.out.println(++num);}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*/public class ScopeTestController {private int num = 0;public void testScope() {System.out.println(++num);}public void testScope2() {System.out.println(++num);}}
單例是不安全的,會(huì)導(dǎo)致屬性重復(fù)使用。
解決方案
不要在controller中定義成員變量。 萬(wàn)一必須要定義一個(gè)非靜態(tài)成員變量時(shí)候,則通過(guò)注解@Scope(“prototype”),將其設(shè)置為多例模式。 在Controller中使用ThreadLocal變量
補(bǔ)充說(shuō)明
推薦閱讀:
美國(guó)如果把根域名服務(wù)器封了,中國(guó)會(huì)從網(wǎng)絡(luò)上消失?
這款小眾的賺錢機(jī)器「上不封頂,下有保底」,千萬(wàn)不要告訴別人!
微信掃描二維碼,關(guān)注我的公眾號(hào)
朕已閱?
評(píng)論
圖片
表情

