@Component
public class OrderServiceImpl implements OrderService {
private final MemberRepository memberRepository;
private final DiscountPolicy discouontPolicy;
@Autowired // 생성자가 1개만 있는 경우는 생략 가능
public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
}
@Component
public class OrderServiceImpl implements OrderService {
private MemberRepository memberRepository;
private DiscountPolicy discouontPolicy;
@Autowired
public void setMemberRepository(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
@Autowired
public void setDiscountPolicy(DiscountPolicy discountPolicy) {
this.discountPolicy = discountPolicy;
}
}
@Component
public class OrderServiceImpl implements OrderService {
@Autowired
private MemberRepository memberRepository;
@Autowired
private DiscountPolicy discountPolicy;
}
@Component
public class OrderServiceImpl implements OrderService {
private MemberRepository memberRepository;
private DiscountPolicy discountPolicy;
@Autowired
public void init(MemberRepository memberRepository, DiscountRepository discountRepository) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
}
정리
생성자 주입
방식을 선택하자
@Autowired
는 타입으로 조회한다.
문제가 되는 경우
@Component
public class FixDiscountPolicy implements DiscountPolicy {}
@Component
public class RateDiscountPolicy implements DiscountPolicy {}
@Autowired
private DiscountPolicy discountPolicy;
NoUniqueBeanDefinitionException
발생
해결 방법을 알아보자.
// 변경 전
@Autowired
private DiscountPolicy discountPolicy
// 필드 명을 빈 이름으로 변경 후
@Autowired
private DiscountPolicy rateDisountPolicy
@Qualifier
끼리 매칭NoSuchBeanDefinitionException
발생빈 동록시 @Qualifier
를 붙여준다.
@Component
@Qualifier("mainDiscountPolicy")
public class RateDiscountPolicy implements DiscountPolicy {}
주입 시 @Qualifier
를 붙여주고 등록한 이름을 적어준다.
// 생성자 자동 주입 예시
@Autowired
public OrderServiceImpl(MemberRepository memberRepository,
@Qualifier("mainDiscountPolicy") DiscountPolicy discountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
// rateDiscountPolicy가 우선권을 갖는다.
@Component
@Primary
public class RateDiscountPolicy implements DiscountPolicy {}
@Component
public class FixDiscountPolicy implements DiscountPolicy {}
Reference
인프런 - 김영한님의 [스프링 핵심 원리 - 기본편] 수강 후 강의노트를 바탕으로 작성한 글입니다.
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%95%B5%EC%8B%AC-%EC%9B%90%EB%A6%AC-%EA%B8%B0%EB%B3%B8%ED%8E%B8/dashboard