Spring的Controller是单例还是多例?怎么保证并发的安全
阅读本文大概需要 2 分钟。
controller默认是单例的,不要使用非静态的成员变量,否则会发生数据逻辑混乱。正因为单例所以不是线程安全的。
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);}}
单例是不安全的,会导致属性重复使用。
解决方案
不要在controller中定义成员变量。 万一必须要定义一个非静态成员变量时候,则通过注解@Scope(“prototype”),将其设置为多例模式。 在Controller中使用ThreadLocal变量
补充说明
推荐阅读:
这款小众的赚钱机器「上不封顶,下有保底」,千万不要告诉别人!
微信扫描二维码,关注我的公众号
朕已阅 
评论

