跳到主要内容

使用泛型作为自动装配限定符

ChatGPT-4o 中英对照 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();
}
}
java

假设前面的 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
java

泛型限定符在自动装配列表、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;
java