创建一个普通的spring project,后编写如下控制器:
@RestController
public class TestController{
private static int a = 0; // 静态变量
private int b = 0; // 非静态
@GetMapping("test")
String test(){
System.out.println(a++ + " | " + b++);
return a++ + " | " + b++;
}
}
默认为单例模式
浏览器访问后打印:
0 | 0
1 | 1
2 | 2
3 | 3
4 | 4
这时改为多例模式操作一下,即在类上加入@Scope("prototype")
,如下:
@RestController
@Scope("prototype")
public class TestController{
private static int a = 0; // 静态变量
private int b = 0; // 非静态
@GetMapping("test")
String test(){
System.out.println(a++ + " | " + b++);
return a++ + " | " + b++;
}
}
打印如下:
0 | 0
1 | 0
2 | 0
3 | 0
4 | 0
当然,spring一般是通过IOC(控制注入)来管理bean的,所以可以通过@Bean和Scope这两个注解结合来设置bean的原型模式,示例:
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public TestBean getTestBean() {
return new TestBean();
}
由此得出:定义一个非静态成员变量时候,则通过注解@Scope(“prototype”),将其设置为多例(原型)模式。这也是最常用的一种情况。