[spring]多種類の依存関係注入(DI)方法
インプラント作成者
생성자가 1개면 @Autowired 생략해도됨
@Component
public class OrderServiceImpl implements OrderService {
private final MemberRepository memberRepository;
private final DiscountPolicy discountPolicy;
@Autowired
public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy
discountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
}
注入モディファイヤ(setter)
@Component
public class OrderServiceImpl implements OrderService {
private MemberRepository memberRepository;
private DiscountPolicy discountPolicy;
@Autowired
public void setMemberRepository(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
@Autowired
public void setDiscountPolicy(DiscountPolicy discountPolicy) {
this.discountPolicy = discountPolicy;
}
}
- 필드 주입
- 외부에서 변경이 불가능해서 테스트가 힘듦
- 테스트목적의 특별한 용도에서 사용(코드가 짧음)
- DI 프레임워크가 없으면 아무것도 안됨
- 사용 비추천
```java
@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, DiscountPolicy
discountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
}
Reference
この問題について([spring]多種類の依存関係注入(DI)方法), 我々は、より多くの情報をここで見つけました https://velog.io/@isntkyu/spring-다양한-의존관계-주입-DI-방법テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol