將泛型作為自動裝配限定詞
除了 @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>>