Spring的Controller是怎么保证并发的安全

发布时间:2021-12-02 16:19:45 作者:柒染
来源:亿速云 阅读:183

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 业余草,公众号
 */
@Controller
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,得到的答案是 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是怎么保证并发的安全问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. Java 并发编程(四):如何保证对象的线程安全性
  2. SSL证书是怎么保证网站安全的

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring controller

上一篇:ADO.NET Entity Framework举例分析

下一篇:tk.Mybatis插入数据获取Id怎么实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》