SpringBoot 检索现有原型 bean [英] SpringBoot retrieve existing prototype beans

查看:76
本文介绍了SpringBoot 检索现有原型 bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我的标题,有没有办法检索那些现有的原型bean?我有一个名为A"的原型 bean,并调用 applicationContext.getBean() 方法 10 次以创建 10 个实例.没有引用这些实例的变量.

As my title, is there a way to retrieve those existing prototype bean? I have a prototype bean called "A", and called applicationContext.getBean() method 10 times to create 10 instances. There is no variable referring to those instances.

我尝试过但不起作用的方法:

Ways I have tried but doesn't work:

1.自动装配A的列表如下:

1.autowiring a list of A as below:

@autowired
List<A> as;

这只能得到我创建的最后一个实例.

this can only get the last instance I created.

  1. 如果我使用 beanFactory 来获取 bean,它只会创建一个新的实例 A.

推荐答案

这些bean不会被spring容器管理,你必须自己做,所以你应该创建一个集合来存储它们,只需要实现InitializingBean 存储它

these beans will not be managed by spring container, you must do it by yourself, so you should create a collection to store them, just implements InitializingBean to store it

public class A implements InitializingBean {
    public static final List<A> STORES = new ArrayList<>();
    @Override
    public void afterPropertiesSet() throws Exception {
        A.STORES.add(this);
    }
}

这篇关于SpringBoot 检索现有原型 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆