1

How do I return an arbitrary number of @Bean objects of the same type through a @Configuration class? Something like:

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

Obviously the snippet won't compile, but how would I achieve the result?

newToScala
  • 397
  • 4
  • 16
  • Possible duplicate of [Handling several implementations of one Spring bean/interface](http://stackoverflow.com/questions/11777079/handling-several-implementations-of-one-spring-bean-interface) – Issam El-atif Oct 19 '16 at 15:56
  • you can't, the myBean method must return a single instance of a class, the in-code configuration only replaces the xml one, you provide a name or a type and you get the required bean, if you need many different beans you'll need many methods annotated with @Bean for each one of those – OscarG Oct 19 '16 at 15:57
  • @Isaam Not a duplicate. This is an arbitrary number of beans. Using Qualifier only works for a predefined set. – newToScala Oct 19 '16 at 16:09
  • @Oscar I understand that a method that returns one bean can only return one bean. I am asking how to add an arbitrary number of beans into the application context based on a configuration property. – newToScala Oct 19 '16 at 16:10

1 Answers1

0

I ended up doing this:

 @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)
    }
  }
newToScala
  • 397
  • 4
  • 16