kim.zhang

风在前,无惧!


  • 首页

  • 标签42

  • 分类12

  • 归档94

  • 搜索

SpringBoot注入多例的Bean.md

发表于 2020-10-14 更新于 2021-11-21 分类于 SpringBoot
本文字数: 1.7k 阅读时长 ≈ 2 分钟

SpringBoot如何注入多例Bean?

SpringBoot默认是注入单例模式的Bean,可以在Bean上添加@Scope(value = “prototype”)注解来注入多例的Bean。

1
2
3
@Component
@Scope(value = "prototype")
public class CouponChecker {}

使用成员变量的方式注入CouponChecker实例。

1
2
3
4
5
6
7
8
9
10
11
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
CouponChecker couponChecker;

@GetMapping("/prototype")
public void test(){
System.out.println(couponChecker);
}
}

输出结果:

多次访问后,控制台打印如下。我们可以看到多次打印的hasd值都是一样的,那是不是说明@Scope注解没有生效,注入的还是单例的Bean呢?

1
2
com.sise.ming.logic.CouponChecker@347a792b
com.sise.ming.logic.CouponChecker@347a792b

其实不然,此时已经是多例模式,但由于成员属性的注入只是在类实例实例化的时候注入一次,导出打印出的hash码是一致的。

如果将成员属性的注入方式改为方法属性的注入,可以看到打印的hash值不再一样。

1
2
3
4
5
6
7
8
9
@RestController
@RequestMapping("/test")
public class TestController {

@GetMapping("/prototype")
public void test(@Autowired CouponChecker couponChecker){
System.out.println(couponChecker);
}
}
1
2
com.sise.ming.logic.CouponChecker@43eab93e
com.sise.ming.logic.CouponChecker@26b55617

其他几种注入多例的方式

  • 使用ObjectFactory,缺点是使用的时候需要调用getObject方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @RestController
    @RequestMapping("/test")
    public class TestController {

    @Autowired
    private ObjectFactory<CouponChecker> factory;

    @GetMapping("/prototype")
    public void test(){
    System.out.println(factory.getObject());
    }
    }
  • 使用动态代理,注入的是类选择ScopedProxyMode.TARGET_CLASS,注入的是接口选择ScopedProxyMode.INTERFACES

    1
    2
    3
    @Component
    @Scope(value = "prototype",proxyMode = ScopedProxyMode.TARGET_CLASS)
    public class CouponChecker {}
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @RestController
    @RequestMapping("/test")
    public class TestController {

    @Autowired
    private CouponChecker couponChecker;

    @GetMapping("/prototype")
    public void test(){
    System.out.println(couponChecker);
    }
    }
一毛也是爱~
Kim.Zhang 微信支付

微信支付

# Bean
小程序登录获取JWT令牌.md
Java8日期时间.md
  • 文章目录
  • 站点概览
Kim.Zhang

Kim.Zhang

且行且珍惜
94 日志
12 分类
42 标签
E-Mail Weibo
  1. 1. SpringBoot如何注入多例Bean?
  2. 2. 其他几种注入多例的方式
粵ICP备19091267号 © 2019 – 2022 Kim.Zhang | 629k | 9:32
本站总访问量 4 次 | 有 309 人看我的博客啦 |
博客全站共176.7k字
载入天数...载入时分秒...
0%