0

I'm trying to get Spring Boot dependency injection to allow me to do the following:

interface MyBean

@Component
class MyBeanA : MyBean

@Component
class MyBeanB : MyBean

@Component
class MyBeanConsumer(myBean: MyBean)

Here, Spring complains that there are multiple beans of type MyBean. I would like it to create two instances of MyBeanConsumer. One with MyBeanA and one with MyBeanB. I need to do this for a number of beans, so I'm trying to avoid boilerplate configuration classes like this:

@Configuration
class MyBeanConfiguration {
    @Bean
    fun consumers(myBeans: List<MyBean>) = myBeans.map { MyBeanConsumer(it) }
}

Is this possible in Spring?

F43nd1r
  • 7,690
  • 3
  • 24
  • 62
  • Then you will have multiple instance of `MyBeanConsumer`. How do you want to use them. I mean somewhere in your program you want to use one of them and somewhere the other one? or you want to iterate through them and do something. – Tashkhisi Oct 17 '20 at 22:39
  • Yes, having multiple instances is the plan. I want to use them as a list. – F43nd1r Oct 17 '20 at 22:41

2 Answers2

0

you can use the Qualifier annotation and specify the name of the bean requested.

you can visit this Spring @Autowired and @Qualifier

Elarbi Mohamed Aymen
  • 1,617
  • 2
  • 14
  • 26
  • This does not answer the question. I do not want one instance with a qualified parameter. I want an instance per possible parameter. – F43nd1r Oct 17 '20 at 22:30
0

If everywhere in your program you want to inject them as List of beans you can go with this approach.

@Configuration public MyConfigurationClass {
        
        @Bean
        @Qualifier("mylist")
        public List<MyType> configure() {
            //create your dynamical list here
        }
 }

But if you want to use them as individual bean somewhere in your program and also you want to inject all of them as a List somewhere else you can do that this way:

@Configuration
public class AppConfig implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (int i = 0; i < 3; i++) {
            System.out.println("register my bean: " + i);
            beanFactory.registerSingleton("bean-" + i, new MyBean("MyBean-" + i));
        }
    }

Read the following answer for further detail: How to create multiple beans of same type according to configuration in Spring?

Tashkhisi
  • 2,070
  • 1
  • 7
  • 20
  • This is exactly what I want to avoid: Boilerplate for each of these cases. I stated this in the question. – F43nd1r Oct 26 '20 at 15:04