Using Generics as Autowiring Qualifiers

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

  • Java

  • Kotlin

@Configuration
public class MyConfiguration {

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

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

	@Bean
	fun stringStore() = StringStore()

	@Bean
	fun integerStore() = IntegerStore()
}

假设前述 Bean 实施了一个泛型接口(即 Store<String>Store<Integer>),那么您可以 @Autowire Store 接口,并且泛型将用作限定符,如下例所示:

  • Java

  • Kotlin

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

@Autowired
private Store<Integer> s2; // <Integer> qualifier, injects the integerStore bean
@Autowired
private lateinit var s1: Store<String> // <String> qualifier, injects the stringStore bean

@Autowired
private lateinit var s2: Store<Integer> // <Integer> qualifier, injects the integerStore bean

自动装配列表、Map 实例和数组时,泛型限定符也适用。以下示例将自动装配一个泛型 List

  • Java

  • Kotlin

// 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;
// Inject all Store beans as long as they have an <Integer> generic
// Store<String> beans will not appear in this list
@Autowired
private lateinit var s: List<Store<Integer>>