zoukankan      html  css  js  c++  java
  • Spring的Controller是单例 怎么保证并发的安全

    controller默认是单例的,不要使用非静态的成员变量,否则会发生数据逻辑混乱。正因为单例所以不是线程安全的。

    验证示例:

    @Controller
    public class HelloController {
    
        private int num = 0;
    
        @GetMapping(value = "/testScope")
        @ResponseBody
        public void testScope() {
            System.out.println(++num);
        }
    
        @GetMapping(value = "/testScope2")
        @ResponseBody
        public void testScope2() {
            System.out.println(++num);
        }
    
    }

    首先访问 http://localhost:8081/testScope,得到的是1
    然后再访问 http://localhost:8081/testScope2,得到的是 2

    得到的不同的值,这是线程不安全的。

    controller增加作用多例 @Scope("prototype")

    @Controller
    @Scope("prototype")
    public class HelloController { private int num = 0; @GetMapping(value = "/testScope") @ResponseBody public void testScope() { System.out.println(++num); } @GetMapping(value = "/testScope2") @ResponseBody public void testScope2() { System.out.println(++num); } }

    首先访问 http://localhost:8081/testScope,得到的是1
    然后再访问 http://localhost:8081/testScope2,得到的是 2

    单例是不安全的,会导致属性重复使用。

    解决方案

    1、不要在controller中定义成员变量。
    2、万一必须要定义一个非静态成员变量时候,则通过注解@Scope(“prototype”),将其设置为多例模式。
    3、在Controller中使用ThreadLocal变量

    文章来源:https://blog.csdn.net/riemann_/article/details/97698560

  • 相关阅读:
    JS 语法: document.getElementById没有括号
    c#,WinForm中读写配置文件App.config
    System.Data.SQLite数据库简介
    把JS 脚本嵌入CS运行
    Syteline Receiving By Purchase Orders Report
    TSQL DATEPART() Functions
    TSQL CONVERT Functions
    TSQL CAST Functions
    接口(Interface)替代抽象(Abstract)
    独立子查询
  • 原文地址:https://www.cnblogs.com/ooo0/p/14167458.html
Copyright © 2011-2022 走看看