SpringBoot retrieve existing prototype beans

不羁的心 提交于 2021-01-29 10:56:11

问题


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.

  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!