더북(TheBook)

3장에서 생성자 DI가 좋은 방법이며 필드 주입보다 선호되는 방법이라고 말한 것을 기억하는가? 생성자 주입의 장점 중 하나는 인스턴스를 불변으로 만들 수 있다는 것이다(빈의 필드를 final로 정의). 이전 예제에서 필드 주입을 생성자 주입으로 대체하여 CommentService 클래스 정의를 개선할 수 있다. 더 좋은 클래스 설계는 다음 코드와 같다.

@Service
public class CommentService {

    private final CommentRepository commentRepository; ← 필드를 final로 정의하면 이 필드는 변경될 수 없다는 것을 강조할 수 있다.

    public CommentService(CommentRepository commentRepository) {
        this.commentRepository = commentRepository;
    }

    public CommentRepository getCommentRepository() {
        return commentRepository;
    }
}
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.