跳到主要内容
版本:7.0.3

使用泛型作为自动连接(Autowiring)的限定符

Hunyuan 7b 中英对照 Using Generics as Autowiring Qualifiers

除了@Qualifier注解外,您还可以使用Java泛型类型作为一种隐式的限定形式。例如,假设您有以下配置:

@Configuration
public class MyConfiguration {

@Bean
public StringStore stringStore() {
return new StringStore();
}

@Bean
public IntegerStore integerStore() {
return new IntegerStore();
}
}

假设前面的bean实现了一个泛型接口(即Store<String>Store<Integer>),你可以使用@Autowire来标注Store接口,并且该泛型会作为限定符被使用,如下例所示:

@Autowired
private Store<String> s1; // <String> qualifier, injects the stringStore bean

@Autowired
private Store<Integer> s2; // <Integer> qualifier, injects the integerStore bean

泛型限定符在自动装配列表、Map实例和数组时也同样适用。以下示例展示了如何自动装配一个泛型的List

// Inject all Store beans as long as they have an <Integer> generic
// Store<String> beans will not appear in this list
@Autowired
private List<Store<Integer>> s;