简体   繁体   中英

Spring autowired collection of qualified beans

I have some Spring @Components with @Qualifier annotations, let's say it's in example "A" and "B". I want to inject them (using only annotations) into List. How can I do that ?

@Component
public class WhatIHave {

    @Autowired
    @Qualifier("A")
    private MyType firstBean;

    @Autowired
    @Qualifier("B")
    private MyType secondBean;
    ....
}

@Component
public class WhatIWantToHave {

    @Autowired
    @Qualifier("A", "B") //something like that
    private List<MyType> beans;
    ...
}

Do I need to make it in @Configuration class ?

@Configuration
public class MyConfiguration {

    @Autowired
    @Qualifier("A")
    private MyType firstBean;

    @Autowired
    @Qualifier("B")
    private MyType secondBean;

    @Bean
    public List<MyType> beans() {
        return Lists.newArrayList(firstBean, secondBean);
    }
}

Or there is another way to do that ?

@Qualifier is to know which bean is qualify to autowired on a field in case of same type beans so why not:

@Autowired
@Qualifier("A")
private MyType firstBean;

@Autowired
@Qualifier("B")
private MyType secondBean;

then:

List<MyType> list = new ArrayList<>();
list.add(firstBean);
list.add(secondBean);

How about this workaround

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class TypeCollector implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;
    }

    public <T> List<T> getBeans(Class<T> clazz, String... names) {
        List<T> list = new ArrayList<>();
        for (String name : names) {
            list.add(applicationContext.getBean(name, clazz));
        }
        return list;
    }
}

The you can autowire the TypeCollector and ask for the beans runtime. The disadvantage is that you will get NoSuchBeanDefinitionException at runtime, and you have to use bean names instead of qualifier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM