Spring多个配置相同接口的bean

时间:2016-10-19 15:53:08

标签: java spring

如何通过@Configuration类返回相同类型的任意数量的@Bean对象?类似的东西:

@Configuration
public class MyClass {
  @Bean
  public MyBean myBean {
  for (String myBeanName: getMyBeanNames()) {
    MyBean myBean = new MyBean();
    myBean.setName(myBeanName);
    return myBean
  }
}

显然该片段不会编译,但我如何实现结果呢?

1 个答案:

答案 0 :(得分:0)

我最终这样做了:

 @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)
    }
  }