@Qualifier
🔖 @Qualifier
정의
@Qualifier는 같은 타입의 Bean이 여러 개 있을 때 어떤 Bean을 주입할지 구분하는 애너테이션이다.
@Autowired와 함께 사용하면 Bean 선택을 명시적으로 제어할 수 있다.
🧩 역할
- 동일 타입 Bean 중 하나를 구별한다.
@Autowired의 모호함을 제거한다.- 주입 대상 Bean을 이름 기준으로 선택할 수 있게 한다.
memo
Spring은 동일한 타입의 Bean이 여러 개 있으면 어떤 Bean을 주입해야 할지 알 수 없기 때문에 예외가 발생할 수 있다.
🛠 사용법
Bean 등록 시 이름 지정
@Bean("myWebClient")
public WebClient myWebClient() {
return WebClient.builder().build();
}
Constructor Injection
public class MyClass {
private final WebClient webClient;
@Autowired
public MyClass(@Qualifier("myWebClient") WebClient webClient) {
this.webClient = webClient;
}
}
Setter Injection
public class MyClass {
private WebClient webClient;
@Autowired
public void setWebClient(@Qualifier("myWebClient") WebClient webClient) {
this.webClient = webClient;
}
}
Field Injection
public class MyClass {
@Autowired
@Qualifier("myWebClient")
private WebClient webClient;
}
⚠️ 주의사항
@Qualifier는 Bean 이름과 맞춰서 사용해야 한다.- 이름이 다르면 주입할 Bean을 찾지 못한다.
- 필드 주입보다는 생성자 주입과 함께 쓰는 편이 더 명확하다.
📌 정리
@Qualifier는 같은 타입 Bean이 여러 개일 때 선택을 돕는 애너테이션이다.@Autowired와 함께 사용하면 주입 대상을 명확히 지정할 수 있다.- Bean 이름과 주입 위치를 정확히 맞추는 것이 중요하다.
댓글남기기