Spring 的Controller 是单例or多例

      你什么也不肯放弃,又得到了什么?

背景:今天写代码遇到一个Controller 中的线程安全问题,那么Spring 的Controller 是单例还是多例的呢?若为单例又如何保证并发安全呢?

一、面试回答

Spring管理的Controller,即加入@Controller 注入的类,默认是单例的,因此建议:

1、不要在Controller 中定义成员变量;(单例非线程安全,会导致属性重复使用)

2、若必须要在Controller 中定义一个非静态成员变量,则通过注解@Scope("prototype"),将其设置为多例模式。

二、验证Controller 单例

验证代码:

 package com.ausclouds.bdbsec.tjt;

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; /**
* @author tjt
* @time 2020-08-25
* @desc 验证Controller 单例
*/
@Controller
@ResponseBody
@RequestMapping("/tjt")
public class TestSingleController { private long money = 10; @GetMapping("/test1")
public long testSingleOne(){
money = ++money;
System.out.println("/tjt/test1: the money I have: " + money);
return money;
} @GetMapping("test2")
public long testSingleTwo(){
money = ++money;
System.out.println("/tjt/test2: the money I have: " + money);
return money;
} }

-拍一拍

首先,访问 http://localhost:8088/test1,得到的答案是11

接着,再访问 http://localhost:8088/test2,得到的答案是 12

不难看出:同一个变量,两次访问得到不同的结果,很明显是线程不安全的。

验证截图:

 三、Controller 如何实现多例?

尽量不要在Controller 中定义成员变量,若必须要在Controller 中定义一个非静态成员变量,则通过注解@Scope("prototype"),将其设置为多例模式;或者是在Controller 中使用ThreadLocal 变量。

验证代码:

 package com.ausclouds.bdbsec.tjt;

 import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; /**
* @author tjt
* @time 2020-08-25
* @desc 验证Controller 单例
*/
@Controller
@ResponseBody
@Scope("prototype") // 将Controller 设置为多例模式
@RequestMapping("/tjt")
public class TestSingleController { private long money = 10; @GetMapping("/test1")
public long testSingleOne(){
money = ++money;
System.out.println("/tjt/test1: after use @Scope the money I have: " + money);
return money;
} @GetMapping("test2")
public long testSingleTwo(){
money = ++money;
System.out.println("/tjt/test2: after use @Scope the money I have: " + money);
return money;
} }

-拍一拍

在加上@Scope("prototype")后首先,访问 http://localhost:8088/test1,得到的答案是11

接着,再访问 http://localhost:8088/test2,得到的答案也是 11

不难看出:同一个变量,两次访问得到相同的结果。

验证截图:

四、作用域

其实,spring bean 的作用域除了上面使用的prototype 外,还有singleton、request、session 和global session 四种;其中request、session 和global session 主要运用在Web 项目中。

  • singleton:单例模式,当spring 创建applicationContext 容器的时候,spring会预初始化所有的该作用域实例,加上lazy-init 就可以避免预处理;
  • prototype:原型模式,每次通过getBean 获取该bean 就会新产生一个实例,创建后spring 将不再对其管理;
  • request:每次请求都新产生一个实例,和prototype 不同就是创建后,接下来的管理,spring依然在监听;
  • session:每次会话,同上;
  • global session:全局的web 域,类似于servlet 中的application。

你什么也不肯放弃,又得到了什么?

Spring 的Controller 是单例or多例的更多相关文章

  1. springboot默认创建的bean是单实还是多例

    转:https://blog.csdn.net/q1512451239/article/details/53122687 springboot默认创建的bean是单实还是多例 曾经面试的时候有面试官问 ...

  2. 转:【Spring MVC Controller单例陷阱】

    http://lavasoft.blog.51cto.com/62575/1394669/ Spring MVC Controller默认是单例的: 单例的原因有二:1.为了性能.2.不需要多例. 1 ...

  3. Spring MVC Controller单例陷阱

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://lavasoft.blog.51cto.com/62575/1394669 Spr ...

  4. spring的controller默认是单例还是多例

    转: spring的controller默认是单例还是多例 先看看spring的bean作用域有几种,分别有啥不同. spring bean作用域有以下5个: singleton:单例模式,当spri ...

  5. Spring5源码解析-Spring框架中的单例和原型bean

    Spring5源码解析-Spring框架中的单例和原型bean 最近一直有问我单例和原型bean的一些原理性问题,这里就开一篇来说说的 通过Spring中的依赖注入极大方便了我们的开发.在xml通过& ...

  6. SpringMVC中的Controller默认单例

    众所周知,Servlet是单例的. 在struts中,Action是多例的,每一个请求都会new出来一个action来处理. 在Spring中,Controller默认是单例的,多个请求都会访问同一个 ...

  7. Spring对象类型——单例和多例

    由于看淘淘商城的项目,涉及到了项目中处理spring中bean对象的两种类型,分别是单例和多例,就在此记录一下,方便加深理解,写出更加健壮的代码. 一.单例和多例的概述 在Spring中,bean可以 ...

  8. Spring容器-ApplicationContext的单例设计

    Spring容器-ApplicationContext的单例设计   每次通过new创建一个ApplicationContext容器,都会执行refresh方法,看源代码了解到这个refresh方法会 ...

  9. SSM-Spring-05:Spring的bean是单例还是多例,怎么改变?

    ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- Spring的bean是单例的 它在Spring容器初始化的时候创建对象 可以修改为多例,在此bean节点中添 ...

随机推荐

  1. 下载数据到csv中(乱码),使用numpy , pandas读取失败 解决方案

    读取数据,下载数据到 csv 文件中 allUniv 列表类型[[...],[...]] 字符集编码使用 utf-8-sig with open('文件名.csv','w',newline='',en ...

  2. 部分浏览器 set-cookie 不成功踩坑记录

    事件起因: 公司正在做一个sso的单点登录的项目,做完之后,在测试阶段,不同的终端的兼容测试时候,好几个不同的浏览器出现了不同的问题,有登录之后自动退出,有登陆不成功等问题. 在 pc 端只有 uc ...

  3. 11-Pandas之排序(df.sort_index()、df.sort_values()、随机重排、随机采样)

    排序是一种索引机制的一种常见的操作方法,也是Pandas重要的内置运算,主要包括以下3种方法: 排序方法 说明 sort_values() 根据某一列的值进行排序 sort_index() 根据索引进 ...

  4. Python unichr() 函数

    描述 unichr() 函数 和 chr() 函数功能基本一样, 只不过是返回 unicode 的字符.高佣联盟 www.cgewang.com 注意: Python3 不支持 unichr(),改用 ...

  5. Python os.stat_float_times() 方法

    概述 os.stat_float_times() 方法用于决定stat_result是否以float对象显示时间戳.高佣联盟 www.cgewang.com 语法 stat_float_times() ...

  6. PHP array_product() 函数

    实例 计算并返回数组的乘积: <?php$a=array(5,5);echo(array_product($a));?> 运行实例 » 定义和用法 array_product() 函数计算 ...

  7. CF804D Expected diameter of a tree 树的直径 根号分治

    LINK:Expected diameter of a tree 1e5 带根号log 竟然能跑过! 容易想到每次连接两个联通快 快速求出直径 其实是 \(max(D1,D2,f_x+f_y+1)\) ...

  8. 文件操作之File 和 Path

    转载:https://blog.csdn.net/u010889616/article/details/52694061 Java7中文件IO发生了很大的变化,专门引入了很多新的类: import j ...

  9. 关于python中的 take no arguments 的解决方法

    针对第四章编写的代码出现的错误做一个总结 Traceback (most recent call last): File "H:\image\chapter4\p81_chongxie.py ...

  10. jar包冲突解决

    背景: 新需求需要引入新jar包,引入后发现本地启动没有报错,发到测试环境提示某个bean无法创建,nested exception is java.lang.VerifyError: Bad typ ...