Using Generics as Autowiring Qualifiers

Dev.Hammy·2024년 2월 11일
0

@Qualifier 어노테이션 외에도 Java 일반 유형을 암시적 한정(qualification) 형식으로 사용할 수 있습니다. 예를 들어 다음과 같은 구성이 있다고 가정합니다.

@Configuration
public class MyConfiguration {

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

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

이전 Bean이 제네릭 인터페이스(즉, Store<String>Store<Integer>)를 구현한다고 가정하면 Store 인터페이스를 @Autowire할 수 있으며 다음 예제와 같이 제네릭이 한정자로 사용됩니다.

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

@Autowired
private Store<Integer> s2; // <Integer> qualifier, injects the integerStore bean

제네릭 한정자는 list, Map 인스턴스 및 배열을 자동 연결하는 경우에도 적용됩니다. 다음 예제에서는 제네릭 List을 자동 연결(autowires)합니다.

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

0개의 댓글