昨天單身的你像不像Controller單例


controller默認是單例的,不要使用非靜態(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 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);}}
單例是不安全的,會導(dǎo)致屬性重復(fù)使用。
解決方案
不要在controller中定義成員變量。 萬一必須要定義一個非靜態(tài)成員變量時候,則通過注解@Scope(“prototype”),將其設(shè)置為多例模式。 在Controller中使用ThreadLocal變量
補充說明
—?完?—
歡迎關(guān)注“Java引導(dǎo)者”,我們分享最有價值的Java的干貨文章,助力您成為有思想的Java開發(fā)工程師!
評論
圖片
表情
