@Autowired
public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy
discountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
}
/**생성자(setter) 주입**/
// @Autowired public void setMemberRepository(MemberRepository memberRepository) {this.memberRepository = memberRepository;}
/**필드 주입**/
// @Autowired private final DiscountPolicy discountPolicy;
@Configuration
만 사용)@Autowired(required=false)
: 자동 주입 대상이 없으면 메서드 호출 안 됨org.springframework.lang.@Nullable
: 자동 주입 대상이 없으면 null 입력Optional<>
: 자동 주입 대상이 없으면 Optional.empty
입력@RequiredArgsConstructor
final이 붙은 필드에 생성자를 자동으로 만들어줌
전
@Autowired
public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy
discountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
}
private final MemberRepository memberRepository;
private final DiscountPolicy discountPolicy;
@Autowired 필드 명
@Qualifier
@Qualifier
****끼리 매칭@Component
@Qualifier("mainDiscountPolicy")
public class RateDiscountPolicy implements DiscountPolicy {}
@Component
@Qualifier("fixDiscountPolicy")
public class FixDiscountPolicy implements DiscountPolicy {}
@Autowired
public OrderServiceImpl(MemberRepository memberRepository, @Qualifier("mainDiscountPolicy") DiscountPolicydiscountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
@Primary
@Autowired
시에 여러 빈이 매칭되면 @Primary
가 우선권을 가진다.@Primary
vs @Qualifier
: @Qualifier
우선 순위가 더 높음 @Component
@Primary
public class RateDiscountPolicy implements DiscountPolicy {}
→ 자동 기능 사용
→ 수동 등록 사용(명확하게 표시)