对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

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

除了 @Qualifier 注解之外,您还可以使用 Java 泛型类型作为隐式的资格说明。例如,假设您有以下配置:spring-doc.cadn.net.cn

@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()
}

假设前面的 beans 实现了一个通用接口(即,Store<String>Store<Integer>),你可以 @AutowireStore 接口,并将泛型用作限定符,如下例所示:spring-doc.cadn.net.cn

@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 个实例和数组时也适用。以下示例自动连线一个通用 Listspring-doc.cadn.net.cn

// 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>>