如何通过@Configuration类返回任意数量的相同类型的@Bean对象?就像是:
@Configuration
public class MyClass {
@Bean
public MyBean myBean {
for (String myBeanName: getMyBeanNames()) {
MyBean myBean = new MyBean();
myBean.setName(myBeanName);
return myBean
}
}
显然,该代码段无法编译,但是我如何获得结果?
最佳答案
我最终这样做:
@PostConstruct
public void postConstruct() {
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
for (String myBeanName: getMyBeanNames()) {
MyBean myBean = new MyBean();
myBean.setName(myBeanName);
beanFactory.registerSingleton(myBean.class.getName() + myBean.getName(), myBean)
}
}