自動注入[TIL]依存
多様な依存関係注入方法
インプラント作成者
@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;
}
}
注入モディファイヤ(setter注入)
@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;
}
}
整理する생성자 주입
方式2つ以上の空のクエリ @Autowired
タイプ別クエリー.
問題が発生した場合@Component
public class FixDiscountPolicy implements DiscountPolicy {}
@Component
public class RateDiscountPolicy implements DiscountPolicy {}
@Autowired
private DiscountPolicy discountPolicy;
NoUniqueBeanDefinitionException
オカレンス
解決策を理解してください.
一致@Autowiredフィールド名
@Component
public class FixDiscountPolicy implements DiscountPolicy {}
@Component
public class RateDiscountPolicy implements DiscountPolicy {}
@Autowired
private DiscountPolicy discountPolicy;
// 변경 전
@Autowired
private DiscountPolicy discountPolicy
// 필드 명을 빈 이름으로 변경 후
@Autowired
private DiscountPolicy rateDisountPolicy
@Qualifierの使用
@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;
}
@Primaryの使用
// rateDiscountPolicy가 우선권을 갖는다.
@Component
@Primary
public class RateDiscountPolicy implements DiscountPolicy {}
@Component
public class FixDiscountPolicy implements DiscountPolicy {}
Reference
この問題について(自動注入[TIL]依存), 我々は、より多くの情報をここで見つけました https://velog.io/@ssoyeong/TIL-의존관계-자동-주입テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol