Spring Boot检索现有的原型bean

问题描述 投票:0回答:1

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

我尝试但不起作用的方式:

1.如下所示自动列出A:

@autowired
List<A> as;

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

  1. 如果我使用beanFactory来获取bean,它将只创建一个新的实例A.
spring-boot prototype spring-bean
1个回答
0
投票

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

public class A implements InitializingBean {
    public static final List<A> STORES = new ArrayList<>();
    @Override
    public void afterPropertiesSet() throws Exception {
        A.STORES.add(this);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.