Framework/Spring Boot
[Framework] Spring Boot [@Autowired & private final]
SeungyubLee
2022. 11. 30. 14:21
의존성 주입 방식
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. 오류를 방지할 수 있다.