关于Spring中Bean作用域scope属性常见有两个属性值: singleton(单例)和prototype (原型/多例)。在SpringMVC中默认是singleton(单例),那问题来了:为啥SpringMVC默认是单例呢?
我们知道SpringMVC的控制层是方法级别:每次请求都执行对应的方法
@RestController
//第二次修改为多例
//@Scope("prototype")
public class TestController {
private int i = 0;
@GetMapping(value = "/test1")
public int testInstance1(){
i++;
return i;
}
@GetMapping(value = "/test2")
public int testInstance2(){
i++;
return i;
}
}
第一次单例模式
依次访问
http://localhost:8082/reed/test1 //返回1
http://localhost:8082/reed/test1 //返回2
http://localhost:8082/reed/test2 //返回3
可以看出。所以请求共享一个对象
//////////////////////////////////////////////////////
第二次多例模式
http://localhost:8082/reed/test1 //返回1
http://localhost:8082/reed/test1 //返回1
http://localhost:8082/reed/test2 //返回1
可以看出变为多例,每次请求新建一个对象
所以一般情况下,Springmvc没特殊需求用到控制层共享变量,每次请求都对应每次调用的方法,请求发送的参数既是方法接收的参数,并不担心方法之间脏数据的问题,而且单例不用像多例那样每次都去创建对象,要快得多。
有一点值得注意的是,在struts2中默认是多例,因为其和springmvc不同,它每次请求都对应一个action,而action是类级别的,action类中可能存在很多的方法, struts2接收参数的方式一般是通过在action中定义成员变量或JavaBean来实现的 ,所以说这时struts2为了防止有脏数据就需要设置多例了。
来源:oschina
链接:https://my.oschina.net/u/4247262/blog/3196646