问题
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 ?
回答1:
@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);
回答2:
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.
来源:https://stackoverflow.com/questions/41129388/spring-autowired-collection-of-qualified-beans