[Spring] 생성자 주입방식을 권장하는 이유
의존성 주입방법은 3가지가 있다.
1. 필드주입
2. Setter주입
3. 생성자주입
필드주입은 가장 간결한방법으로 아직까지도 많은 개발자들이 사용을 하고 있다.
왜 생성자 주입방식이 좋나?
생성자 주입 방식이 좋은 방식이라는 것은 많은 개발자들 사이에서 이미 가정사실화가 됐으며
공식문서에도 말하고있다.
https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html#beans-constructor-injection (공식문서 setter vs constructot)
Dependency Injection :: Spring Framework
Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency. Calling a static factory method with specific arguments to construct the bean is nearly equivalent, and this discussion
docs.spring.io
생성자주입의 장점
- 순환참조를 방지할 수 있다. *******
---> 기존 필드참조나 Setter참조에서는 순환참조를 못걸러내서, 결국 StackoverFlowError 를 밷고 죽음
------> 생성자주입방식은 앱구동시 실패가 떨어지므로 방지할 수 있다.
- 의존성주입시 final로 선언 가능
- 의존관계가 설정이 되지 않으면 객체생성 불가 -> 컴파일시 인지 가능, NPE방지
필드주입의 장점?
- 편하다.....