지난 포스트에 이어서 같은 상황일 때, @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와 @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 보다 높기 때문이다.