Spring
[Spring] DI(Dependency Injection) 의존성 주입
Apère
2023. 2. 15. 13:09
반응형
DI(의존성주입)이란 클래스간의 의존관계를 외부에서 주입해주는것을 의미합니다
아래코드와 같이 TestService 클래스에 간단한 덧셈 메서드가 있습니다
public class TestService {
public int sum(int a , int b) {
return a+b;
}
}
이 메서드를 TestController 클래스에서 사용한다고 하면 아래와 같이 됩니다
public class TestController {
private final TestService testService;
public TestController(TestService testService) {
this.testService = testService;
}
public int sum(int a, int b) throws Exception {
return testService.sum(a, b);
}
}
이렇게 되면 TestController는 TestService와 의존관계를 가진다라고 할수 있습니다.
Spring에서는 의존관계를 바탕으로 컨테이너가 주입해줌으로써 TestController에서 TestService의 메서드를 사용할 수 있게 됩니다.
DI를 활용하므로써 장점
- 의존성이 줄어든다
- 코드의 재사용성이 높다
- 테스트하기 좋은코드가 된다
- 가독성이 좋다
반응형