SpringBoot 检索现有原型 bean [英] SpringBoot retrieve existing prototype beans
问题描述
作为我的标题,有没有办法检索那些现有的原型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.
- 如果我使用 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屋!