Spring的Controller是怎么保证并发的安全,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
Controller 默认是单例的,不要使用非静态的成员变量,否则会发生数据逻辑混乱。正因为单例所以不是线程安全的。
我们下面来简单的验证下:
package com.xttblog.springbootdemo.controller;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;/** * @author 业余草,公众号 */@Controllerpublic 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.xttblog.springbootdemo.controller;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;/** * @author 业余草,公众号 */@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。
相信大家不难发现:
❝单例是不安全的,会导致属性重复使用。
❞
spring bean 作用域有以下 5 个:
(下面是在web项目下才用到的)
关于Spring的Controller是怎么保证并发的安全问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/3677838/blog/4822130