불변, 필수 의존관계에 사용
생성자 호출 시점에 딱 한 번만 생성된다.
생성자가 하나면 @Autowired 안 해줘도 자동으로 의존관계 주입이 일어남.
final을 통해서 반드시 값이 있어야 한다.
@component
public class OrderServiceImpl implements OrderService{
private final MemberRepository memberRepository;
@Autowired
public OrderServiceImpl(MemberRepository memberRepository){
this.memberRepository = memberRepository;
}
}
@component
public class OrderServiceImpl implements OrderService{
private final MemberRepository memberRepository;
@Autowired
public void setMemberRepository(MemberRepository memberRepository){
this.memberRepository = memberRepository;
}
}
e.g) 자바빈 프로퍼티 : 필드의 값을 직접 변경하지 않고, set,get Method를 활용해서 값을 읽거나 수정하는 규칙.
@component
public class OrderServiceImpl implements OrderService{
@Autowired private final MemberRepository memberRepository;
}
@component
public class OrderServiceImpl implements OrderService{
private MemberRepository memberRepository;
@Autowired
public void init(MemberRepository memberRepository){
this.memberRepository = memberRepository;
}
}