스프링 핵심 원리 기본편
할인 정책을 바꾸려면 OrderServiceImpl 코드를 변경해야 함
- 역할과 구현을 충실하게 분리O
- 다형성 활용O, 인터페이스와 구현 객체를 분리함
- OCP, DIP 객체 지향설계 원칙을 충실히 준수한 것처럼 보이지만 사실은 아님
DIP: 주문서비스 클라이언트(OrderServiceImpl)은 DiscountPolicy 인터페이스에 의존하면서 DIP를 지킨 것 같은데?
추상인터페이스 뿐만 아니라 구현 클래스에도 의존하고 있음
- 추상 인터페이스: DiscountPolicy
- 구현 클래스: FixDiscountPolicy, RateDiscountPolicy
OCP: 변경하지 않고 확장?
지금은 기능을 확장해서 변경하면 클라이언트 코드에 영향을 줌
DIP 위반 → 추상(인터페이스)만 의존하도록 의존관계를 변경
누군가가 클라이언트인 OrderServiceImpl에 DiscountPolicy의 구현 객체를 대신 생성하고 주입해주어야 한다
현재는 클라이언트가 직접 구현체를 선택하게 되어 있음
→ 관심사를 분리하자
AppConfig : 애플리케이션의 실제 동작에 필요한 구현 객체를 생성
리팩터링
- 메서드명으로 역할이 다 드러남
- 나중에 구현 클래스가 바뀌면 함수 반환형만 바꾸면 됨
- 역할과 구현 클래스가 한눈에 들어옴
- 애플리케이션 전체 구성이 어떻게 되어있는지 빠르게 파악할 수 있음
- 변경을 위해서 AppConfig만 변경하고, 사용 영역에 있는 코드는 변경할 필요 없음
IoC DI 컨테이너
제어의 역전 IoC(Inversion of Control)
기존 프로그램은 구현 객체가 스스로 필요한 서버 구현 객체를 생성, 연결, 실행함
한마디로 구현 객체가 프로그램의 제어 흐름을 스스로 조종
반면 AppConfig가 등장한 이후에 구현 객체는 자신의 로직을 실행하는 역할만, 프로그램의 제어 흐름은 AppConfig가 가져감
OrderServiceImpl
은 필요한 인터페이스들을 호출하지만 어떤 구현 객체들이 실행될지 모름
프로그램에 대한 제어 흐름에 대한 권한은 모두 AppConfig가 가지고 있음
제어의 역전 = 프로그램의 제어 흐름을 직접 제어하는 것이 아니라 외부에서 관리하는 것
- 프레임워크 vs 라이브러리
프레임워크: 내가 작성한 코드를 제어하고 대신 실행 (JUnit)
라이브러리: 내가 작성한 코드가 직접 제어의 흐름을 담당
의존관계 주입 DI(Dependency Injection)
OrderServiceImpl은 DiscountPolicy 인터페이스에 의존, 실제 어떤 구현 객체가 사용될지는 모른다
의존관계는 정적인 클래스 의존 관계와 실행 시점에 결정되는 동적인 객체(인스턴스) 의존 관계 둘을 분리해서 생각해야 한다
- 정적인 클래스 의존관계
- 클래스가 사용하는 import 코드만 보고 의존관계를 쉽게 판단할 수 있음
- 정적인 의존 관계는 애플리케이션을 실행하지 않아도 분석할 수 있다
- 동적인 객체 인스턴스 의존 관계
- 애플리케이션 실행 시점에 생성된 객체 인스턴스의 참조가 연결된 의존 관계
애플리케이션 실행 시점에 외부에서 실제 구현 객체를 생성하고 클라이언트에 전달해서 클라이언트와 서버의 실제 의존관계가 연결되는 것을 “의존 관계 주입” 이라 한다.
객체 인스턴스를 생성하고 그 참조값을 전달해서 연결
의존관계 주입을 사용하면 클라이언트 코드를 변경하지 않고 클라이언트가 호출하는 대상의 타입 인스턴스를 변경할 수 있다
정적인 클래스 의존관계를 변경하지 않고(애플리케이션 코드를 변경하지 않고) 동적인 객체 인스턴스 의존관계를 쉽게 변경할 수 있다
IoC 컨테이너, DI 컨테이너
객체를 생성하고 관리하면서 의존관계를 연결해주는 것
의존 관계 주입에 초점을 맞추어 최근에는 주로 DI 컨테이너라 함
'BackEnd > Spring' 카테고리의 다른 글
[Spring] 스프링 핵심 원리 기본편 - 6. 컴포넌트 스캔 (0) | 2022.10.23 |
---|---|
[Spring] 스프링 핵심 원리 기본편 - 5. 싱글톤 컨테이너 (0) | 2022.10.21 |
[Spring] 스프링 핵심 원리 기본편 - 4. 스프링 컨테이너와 빈 (0) | 2022.10.21 |
[스프링/자바] 좋은 객체 지향 설계의 5가지 원칙: SOLID (0) | 2022.10.17 |
[Spring] 제어 역전 IoC와 의존성 주입 DI (0) | 2022.10.11 |