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>)를 구현한다고 가정하면, 다음 예제와 같이 Store 인터페이스에 @Autowire 하고 제네릭을 한정자로 사용할 수 있습니다:

  • 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 인스턴스 및 배열을 autowiring할 때도 적용됩니다. 다음 다음은 일반 `List`를 autowiring하는 예제입니다:

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