erea

Setter DI vs. Constructor DI in Spring 본문

dev/spring boot

Setter DI vs. Constructor DI in Spring

erea 2018. 6. 25. 10:20

spring에서 autowired를 통해 setter di를 하면 inteliJ warning에

always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies

이런 메시지가 뜰때가 있다.


Since Boot 1.4 @Autowired has been optional on constructors. 
You can just tag the constructor with @Autowired if you want to be explicit about it.
Generally speaking you should favour Constructor > Setter > Field injection. Injecting directly to the field misses the point of DI,
 it also means your tests are reliant on Spring to inject dependencies into rather than just being able to pass mocks or stubs directly to it. 
Jurgan Holler has stated that he would remove field injection if at all possible.


Spring 4.3부터는 Spring Bean으로 구성된 클래스가 오직 하나의 생성자를 가지면 Autowired 주석을 생략 할 수 있고 Spring은 해당 생성자를 사용하고 필요한 모든 의존성을 주입 할 것이다.

또한 Spring Framework 5.0에서 @Nullable 주석 (JSR-305의 javax.annotation.Nullable과 같은 모든 패키지의 모든 종류)을 사용할 수도 있습니다.

기본 생성자 관련 : 기본 생성자, 여러 생성자가있을 때 Autowired 주석이있는 생성자 또는 Autowired 주석이 있거나없는 클래스에 하나의 생성자 만 필요합니다.


즉 기존 setter di를 쓰게되면 class들끼리의 coupling이 높아지고 Spring framework에 대한 의존성이 높아지게 됩니다.. 이로 인해서 유닛 테스팅이 힘들어진다는 크나큰 단점이 있습니다.



기존 setter di

@Autowired
private TestService testService;

변경 constructor di

private final PodsService podsService;

@Autowired
public TestController(TestService testService) {
	this.testService = testService;
}


결론

기존 setter di 의 경우 testcode에 의존성주입에 실패하는경우가 생길수 있고 spring 5.0부터는 nullable도 지원되니 
constructor di를 추천한다.


'dev > spring boot' 카테고리의 다른 글

spring boot ssl  (1) 2019.01.02
Spring boot devtools hot swapping by intelij  (0) 2018.07.05
spring boot 2.0 hibernate 5 mysql auto increment  (0) 2018.06.25
spring boot http client ssl 체크 패스하기  (0) 2018.06.25
spring boot  (0) 2018.06.24
Comments