转载自编走编想的博客Spring 4 支持基于泛型的依赖注入
在 4.0 版本之前,Spring 的依赖注入已经部分支持了泛型。例如,在 Spring 3.2 中
@Autowired
private List<MyType> beans;
// 所有扩展 MyType 的 bean 都将注入
但是在 4.0 以前,泛型并没有被当做 Spring 的一种 Qualifier。所以,如果你有如下的配置:
@Configuration
public class MyConfiguration {
@Bean
public Store<String> stringStore() {
return new StringStore();
}
@Bean
public Store<Integer> integerStore() {
return new IntegerStore();
}
}
当你在 Spring 3.2 中尝试 @Autowire Store 时,你将得到如下的错误:
"No qualifying bean of type [Store] is defined: expected single matching bean but found 2: stringStore, integerStore"
这个错误消息的意思是 Spring 发现有两个类型为 Store 的 bean,而无法分辨要 Autowire 哪个。
而从 Spring 4.0 开始,泛型也会被当做是一种 Qualifier
,使得依赖注入可以区分不同的泛型。
@Autowired
private Store<String> s1; // Injects the stringStore bean
@Autowired
private Store<Integer> s2; // Injects the integerStore bean