问题
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.autowiring a list of A as below:
@autowired
List<A> as;
this can only get the last instance I created.
- if I using beanFactory to get bean, it will just create a new instance A.
回答1:
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);
}
}
来源:https://stackoverflow.com/questions/52376526/springboot-retrieve-existing-prototype-beans