Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

조회시 2개의 빈이 충돌하는 문제 #5

Open
CODe5753 opened this issue Apr 17, 2022 · 0 comments
Open

조회시 2개의 빈이 충돌하는 문제 #5

CODe5753 opened this issue Apr 17, 2022 · 0 comments
Labels
bug Something isn't working

Comments

@CODe5753
Copy link
Owner

CODe5753 commented Apr 17, 2022

What

orderServiceImpl에서 DiscountPolicy를 주입 받는다.
기존 코드에서는 RateDiscountPolicyComponent로 등록되어 문제가 없었으나
만약 FixDiscountPolicyComponent로 등록하게 되는 경우
DiscountPolicy를 조회하는 경우 2개의 빈이 조회되는 문제가 발생한다.

Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'hello.core.discount.DiscountPolicy' available: expected single matching bean but found 2: fixDiscountPolicy,rateDiscountPolicy

How

조회 대상 빈이 2개 이상일 때 대처법

Autowired 필드 명 매칭

  1. 타입으로 확인 -> 기존은 필드명도 discountPolicy 였으므로 2번 역할이 무의미하다
  2. 타입 매칭의 결과가 2개 이상일 때 필드명, 파라미터명으로 확인
    @Autowired
    public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy fixDiscountPolicy) {
        this.memberRepository = memberRepository;
        this.discountPolicy = fixDiscountPolicy;
    }

필드명을 fixDiscountPolicy로 지정하는 경우 문제 없이 돌아가는 것을 알 수 있다.

Qualify 사용

Qualify는 추가 구분자를 붙여주는 방법이다.

    @Autowired
    public OrderServiceImpl(MemberRepository memberRepository, @Qualifier("fixDiscountPolicy") DiscountPolicy discountPolicy) {
        this.memberRepository = memberRepository;
        this.discountPolicy = discountPolicy;
    }
  1. Qualifier끼리 매칭
  2. 빈 이름 매칭
  3. NoSuchBeanDefinitionException 발생
    QualifierQualifier가 붙은 애들끼리 찾을 때 사용하는게 유용하다.

단점

  • @Qualifer를 쓰는 쪽도 등록하는 쪽도 모두 붙여주어야 함
  • 문자열 비교이므로 컴파일시 에러가 발생하지 않아 개발자 실수로 에러가 발생할 수 있음
      @Qualifier("mainn")
    • 이 경우 @Qualifier를 포함한 커스텀 어노테이션으로 해결이 가능함
    • 단, 스프링에서 이미 지원하고 있는 기능은 아닌지 판단이 필요하고 커스텀 어노테이션을 무분별하게 사용하는 것은 지양

Primary 사용

Primary는 우선순위를 정하는 방법이다.
우선 순위가 높은 빈에 @Primary를 붙여주면 된다.

Qualifier와 Primary의 우선권

늘 그렇지만 수동에 가까운 쪽이 더 높은 우선권을 갖게 된다.
이 경우 @Qualifier@Primary보다 높은 우선권을 갖는다.

@CODe5753 CODe5753 added the bug Something isn't working label Apr 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant