@Primary와 @Qualifier

jayk·2023년 7월 4일

Spring Injection

목록 보기
3/3

지난 포스트에 이어서 같은 상황일 때, @Primary 어노테이션을 사용한다면 어떻게 될까?

@Configuration
public class InjectionConfig {
	@Primary
    @Bean
    public ObjectMapper aaaObjectMapper() {
        return new ObjectMapper();
    }

    @Bean
    public ObjectMapper bbbObjectMapper() {
        return new ObjectMapper();
    }
}
public class InjectionTest {
    @Autowired
    private ObjectMapper aaaObjectMapper;

    @Autowired
    private ObjectMapper bbbObjectMapper;

    @Test
    void test() {
        System.out.println(">>> " + aaaObjectMapper);
        System.out.println(">>> " + bbbObjectMapper);
    }
}
>>> com.fasterxml.jackson.databind.ObjectMapper@280a258d
>>> com.fasterxml.jackson.databind.ObjectMapper@280a258d

결과는 놀랍게도(?) 같은 값이 나온다.

이유는 다음과 같다.

  • @Primary 어노테이션을 사용하면, bean name을 무시하고 Type만으로 Bean을 주입한다.

이번엔 @Primary와 @Qualifier를 둘 다 써보자

@Configuration
public class InjectionConfig {
	@Primary
    @Bean
    public ObjectMapper aaaObjectMapper() {
        return new ObjectMapper();
    }

    @Bean
    public ObjectMapper bbbObjectMapper() {
        return new ObjectMapper();
    }
}
public class InjectionTest {
    @Autowired
    private ObjectMapper aaaObjectMapper;

    @Autowired
    @Qualifier("bbbObjectMapper")
    private ObjectMapper bbbObjectMapper;

    @Test
    void test() {
        System.out.println(">>> " + aaaObjectMapper);
        System.out.println(">>> " + bbbObjectMapper);
    }
}
>>> com.fasterxml.jackson.databind.ObjectMapper@280a258d
>>> com.fasterxml.jackson.databind.ObjectMapper@bae32f

이번엔 각각 다른 bean이 주입된 것을 볼 수 있다.
@Qualifier의 우선 순위가 @Primary 보다 높기 때문이다.

  • aaaObjectMapper는 @Primary로 선언된 Bean으로 주입된다. (같은 Type이기 때문)
  • bbbObjectMapper는 @Qualifier에 명시된 "bbbObjectMapper" Bean name을 가진 Bean으로 주입된다.

*참고(https://tech.kakaopay.com/post/martin-dev-honey-tip-2/)

0개의 댓글