Alternative way instead of using Autowired
purpose : make test mock injection easy ++
Best practice :: with annotaion of @RequiredArgsConstructor :
inject mock with constructor
differences : make constructor with final args
because repository made or injected never change.
import org.springframework.beans.factory.annotation.Autowired;
@Service
@Transactional(readOnly = true) // get이 더 많은 경우
@RequiredArgsConstructor
public class MemberService {
// @Autowired not used here
private final MemberRepository memberRepository;
...
}
with Autowried on member feild
cons : Not easy to test
import org.springframework.beans.factory.annotation.Autowired;
@Service
@Transactional(readOnly = true) // get이 더 많은 경우
public class MemberService {
@Autowired
private MemberRepository memberRepository;
...
}
with Autowried on method to set
good for injecting mock but not perfect in production mode
@Autowired
public void setMemberRepository(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
with annotaion of @AllArgsConstructor :
inject mock with constructor
make constructor with all args
pros : Good for testing
import org.springframework.beans.factory.annotation.Autowired;
@Service
@Transactional(readOnly = true) // get이 더 많은 경우
@AllArgsConstructor // 모든 필드에 대한 생성자 모두 컨트스럭터 등 생성해줌
public class MemberService {
// @Autowired not used here
private MemberRepository memberRepository;
...
}