本篇文章为大家展示了如何验证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 项目中。
上述内容就是如何验证Spring 中的Controller 是单例还是多例,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。