這裏是我的代碼:如何使用相同的@Qualifier注入bean列表?
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.util.List;
@Configuration
public class ResourceTest {
@Bean
TestBean testBean() {
return new TestBean();
}
@Bean
TargetBean targetBean() {
return new TargetBean("bean1");
}
@Bean(name = "myBean")
TargetBean targetBean2() {
return new TargetBean("bean2");
}
@Bean(name = "myBean")
TargetBean targetBean3() {
return new TargetBean("bean3");
}
public static void main (String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
ResourceTest.class);
TestBean bean = context.getBean(TestBean.class);
System.out.println(bean.getTargetBeanList());
}
public static class TestBean {
private List<TargetBean> targetBeanList;
@Resource(name = "myBean")
public void setXList (List<TargetBean> targetBeanList) {
this.targetBeanList = targetBeanList;
}
public List<TargetBean> getTargetBeanList() {
return targetBeanList;
}
}
public static class TargetBean {
private final String str;
public TargetBean (String str) {
this.str = str;
}
public String getStr() {
return str;
}
@Override
public String toString() {
return "TargetBean{ str='" + str + '\'' +
'}';
}
}
}
輸出: [TargetBean {海峽= 'bean2'}]
預計: 所有豆類資格 「爲myBean」 應該是列表中即bean2和bean3。
根據彈簧REF文檔:
限定符也適用於類型集合,如上所討論的,例如,設置。在這種情況下,根據聲明的限定符的所有匹配的Bean將作爲集合注入。這意味着限定詞不必是唯一的;它們只是構成過濾標準。例如,您可以使用相同的限定符值「action」定義多個MovieCatalog bean,所有這些都將被注入到由@Qualifier(「action」)註釋的Set中。
我使用Spring 4.3.2.RELEASE。請幫助解決這個問題。提前致謝。
太棒了!這樣可行。謝謝。 –