Java/Spring

@Qualifier 어노테이션

Z_Z 2021. 8. 28. 19:42
반응형

보통 @Autowired 어노테이션을 사용해 의존성 자동 주입을 한다.

하지만 @Autowired 어노테이션을 사용해 의존성을 자동 주입하는데 동일한 bean 객체가 2개일 경우 Exception(예외)가 발생한다.

스프링 컨테이너 초기화 과정에서 Exception 예외 발생

* @Autowired 어노테이션을 사용해 의존성 자동 주입 과정에서 bean 객체가 한개여야 하지만

  두개 이상의 bean일 경우 예외 발생

이러한 문제를 해결하기 위해서 @Qualifier 어노테이션이 필요하다.

@Qualifier 어노테이션은 사용할 의존 객체를 선택할수 있다.

@Autowired

@Qualifier(value = "bean 객체 이름")

LicenseService ls;

* @Qualifier 어노테이션에 지정한 value 즉, bean 객체가 존재하지않으면 Exception 발생

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration

public class WebConfig implements WebMvcConfigurer {

@Autowired

@Qualifier(value = "jwtInterceptor")

private HandlerInterceptor interceptor;

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(interceptor)

.addPathPatterns("/**")

.excludePathPatterns("/api/login", "/hello", "/ws/**");

}

}

반응형