springboot中应用prototype

8 篇文章 0 订阅
1 篇文章 0 订阅

创建一个普通的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”),将其设置为多例(原型)模式。这也是最常用的一种情况。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值