Backend/Spring Boot
원본 글 보기

[Spring Boot] @Qualifier, @Primary, @Bean(name)으로 빈 선택하기

[Spring Boot] @Qualifier, @Primary, @Bean(name)으로 빈 선택하기

[Springboot] @Qualifier, @Primary, @Bean(name="")

하나의 서비스에 2개의 datasource 를 사용하려 할 때,

메인 데이터베이스 커넥션에 @Primary 를 사용하여 default 로 설정하고

서브 데이터베이스 커넥션에 @Qualifier 로 명시적으로 의존성을 주입받아 사용할 수 있도록 구성 할 수 있다.

스프링 컨테이너가 올라갈 때, 스프링은 컴포넌트를 스캔하며 빈을 생성한다.

스프링은 싱글톤 전략을 채택하기 때문에 한 가지 타입의 빈은 한 번만 생성되며, 애플리케이션이 구동되는 동안 하나의 빈을 계속하여 사용한다.

하지만 아래와 같이 @Bean으로 생성하는 객체들 중 같은 클래스(타입)인 빈이 있다면 어떨까?



@Configuration
public class Config {

    @Bean
    public Employee JohnEmployee() {
return new Employee("John");
}

    @Bean
    public Employee TonyEmployee() {
return new Employee("Tony");
}
}

스프링은 어느 것을 빈으로 생성하여야 하는지 알 수 없기 때문에 컨테이너를 띄우지 못하고 NoUniqueBeanDefinitionException 예외를 던진다.

이런 경우 다음 두 가지 어노테이션을 사용해 같은 타입의 multiple bean 을 생성할 수 있다.

1. @Primary

Simply put, we use @Primary to give higher preference to a bean when there are multiple beans of the same type. https://www.baeldung.com/spring-primary

@Primary 는 같은 타입의 빈을 2개 이상 생성할 때, 하나의 빈에게 더 높은 선호도를 부여하기 위해 사용한다.

아래 코드를 보자. TonyEmployee() bean 에 @Primary를 붙여, 스프링이 TonyEmployee() bean 의 의존성을 JohnEmployee() 보다 먼저 주입하도록 설정한다. 즉, TonyEmployee 을 default bean 으로 생성한다.



@Configuration
public class Config {

    @Bean
    public Employee JohnEmployee() {
return new Employee("John");
}

    @Bean
    @Primary
    public Employee TonyEmployee() {
return new Employee("Tony");
}
}


2. @Qualifier

By default, Spring resolves autowired entries by type. If more than one bean of the same type is available in the container, the framework will throw NoUniqueBeanDefinitionException, indicating that more than one bean is available for autowiring. https://www.baeldung.com/spring-qualifier-annotation

왜 @Qualifier 가 필요할까?

@Autowired 어노테이션은 스프링에서 빈에 의존성을 주입하기 위해 사용되는 방법이다.

스프링은 타입으로 해당 빈을 찾는다. 그러나 @Autowired 를 통한 의존성 주입 시, 같은 타입의 빈이 하나 이상이라면, autowiring 할 대상이 유니크하지 않기 때문에 마찬가지로 NoUniqueBeanDefinitionException 을 던지게 된다.

아래와 같이 스프링이 주입할 수 있는 bean 후보가 2개가 있다.

Formatter 의 구현체로 FooFormatter 와 BarFormatter 가 빈으로 생성되고, 서비스 레이어에서 의존성을 주입 받도록 하고자 한다.



@Component("fooFormatter")
public class FooFormatter implements Formatter {
public String format() {
return "foo";
}
}

@Component("barFormatter")
public class BarFormatter implements Formatter {
public String format() {
return "bar";
}
}

@Component
public class FooService {

    @Autowired
    private Formatter formatter;
}

하지만 스프링은 두 개의 빈 중 어느 것을 주입하여야 하는지 알지 못하기 때문에 NoUniqueBeanDefinitionException 을 던지게 된다. 이런 문제를 해결하기 위해 @Qualifier를 사용할 수 있다.



public class FooService {
    @Autowired
    @Qualifier("fooFormatter")
private Formatter formatter;
}

형식은 @Qualifier 어노테이션("구현체")

이를 사용하므로써 스프링은 같은 타입의 multiple bean을 제대로 찾을 수 있다.

@Primary 와 마찬가지로, Component 와 함께 사용하여 스프링이 컴포넌트를 스캔하는 과정에서 @Qualifier 를 함께 읽게 할 수 있다.



@Component
@Qualifier("fooFormatter")
public class FooFormatter implements Formatter {
//...
}

@Component
@Qualifier("barFormatter")
public class BarFormatter implements Formatter {
//...
}

3. @Qualifier vs @Primary

@Primary :

같은 타입의 multiple beans 이 존재할 때, 이들 간의 선호도를 정의하여, 하나의 구현체를 default 값으로 사용하게 하는 것. 기본값으로 주입되어야 하는 빈을 특정하고 싶다면 @Primary를 사용하자.

@Qualifier:

다른 빈을 같은 injection point 에서 사용하여야 하는 순간도 있는데, 이 경우 @Qualifier를 사용하여 default 로 주입된 빈이 아닌, 다른 특정 빈을 주입 할 수 있다.

@Qualifier, @Primary 어노테이션이 둘 다 존재할 때는 @Qualifier 가 우선한다. 기본적으로 Primary 는 default 값을 정의하는 반면, Qualifier 는 특정한 값을 정의하기 때문이다.

4. @Bean("name") vs @Component + @Qualifier



@Component
@Qualifier("apple")
public class Apple implements Fruit {
//...
}

@Component 어노테이션은 클래스를 Spring의 빈으로 등록하고,

@Qualifier 어노테이션은 해당 빈에 이름(qualifier)을 부여한다.

즉, Apple 클래스를 스프링 빈으로 등록하고, 해당 빈에 'apple' 이라는 이름을 부여한다.



@Bean("banana")
public Fruit banana() {
//...
return new Banana();
}

@Bean 어노테이션은 banana() 메서드를 사용하여 Banana 객체를 Spring 컨테이너에 빈으로 등록한다.

@Bean("banana")는 "banana"라는 이름의 빈을 등록하고, banana() 메서드가 Banana 객체를 생성하여 반환한다.

@Bean:

@Qualifier:

@Component, @Qualifier를 사용한 방식은 클래스 수준에서 빈을 등록하고, 해당 빈에 qualifier를 부여하는 방식이고

@Bean을 사용한 방식은 메서드 수준에서 빈을 등록하고, 메서드 이름을 빈의 이름으로 사용하는 방식이다.