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


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变量
补充说明
— 完 —
欢迎关注“Java引导者”,我们分享最有价值的Java的干货文章,助力您成为有思想的Java开发工程师!
评论
