@RestController
@RequestMapping("/test")
@Scope("prototype")
public class TestController {
/*静态变量*/
private static int s = 0;
/*非静态的*/
private int i = 0;
@RequestMapping("/test")
public String test() {
System.out.println(s++ + " || " + i++);
return "hello";
}
}
从浏览器直接访问url localhost:8080/test/test
页面显示hello,后台打印如下:
0 || 0
1 || 0
2 || 0
3 || 0
因为spring mvc默认是单例模式,给类上面加了@Scope("prototype"),变成了多例模式。删除这个注解后从新跑程序,会显示如下:
0 || 0
1 || 1
2 || 2
3 || 3
每次访问出现变量共享的情况。在通常状况下少在类级作用域定义变量,防止挖坑。