의존성 주입 방식
1. @Autowired (필드 주입 : Field Injection)
참고 : 필드를 final로 선언 불가
@Service
public class ArticleService {
@Autowired
private ArticleRepository articleRepository;
}
2. private final (생성자 주입 : Constructor Injection)
@Service
public class ArticleService {
private final ArticleRepository articleRepository;
public ArticleService(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
}
private final 방식이 더 좋은 이유
1. 순환 참조를 방지할 수 있다. (순환 참조 발생 시, Application이 구동되지 않는다.)
2. 테스트에 용이하다.
3. final 선언이 가능해 불변성이 보장된다.
4. 코드의 품질을 높일 수 있다.
5. 오류를 방지할 수 있다.
'Framework > Spring Boot' 카테고리의 다른 글
[Framework] Spring Boot [STS 설치 + Git 프로젝트 Import + Tomcat 실행] (1) | 2023.10.05 |
---|---|
[Framework] Spring Boot [JWT] 인증 구현 맛보기 (0) | 2022.11.30 |
[Framework] Spring Boot [TDD] 테스트 코드 작성 (0) | 2022.11.30 |
[Framework] Spring Boot [REST API] 기본 구조 (0) | 2022.11.30 |
[Framework] Spring Boot [JPA + H2] 기초 (0) | 2022.11.30 |