반응형
의존 주입 패턴이란?
public interface Repository {
void someMethod(String articleContent);
}
public class DatabaseRepository implements Repository {
@Override
public void someMethod(String articleContent) {}
}
public class FileRepository implements Repository {
@Override
public void someMethod(String articleContent) {}
}
@Component
public class Service {
private Repository repository;
public void createArticle(String articleContent) {
repository.someMethod(articleContent);
}
}
Service 에서 Repository 의 인스턴스가 Null 이다. 어떻게 해결해야할까?
단순히 new DatabeseRepository(); 를 해주는 것은 문제가 생긴다.
고수준 컴포넌트인 Service 가 저수준 컴포넌트인 DatabeseRepository 를 의존하게 되기 때문이다.
해결책은 Service 의 Repository 구현체를 Service 외부에서 생성하여 Service 에게 주입해야한다.
public class Service {
private Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
public void createArticle(String articleContent) {
repository.someMethod(articleContent);
}
}
public class Client {
public static void main(String[] args) {
Service service = new Service(new DatabaserRepository());
service.createArticle("게시글 내용");
}
}
-> Client 에서 Service 를 생성하면서 파라미터로 Datebaserepository 를 의존성 주입해주고있다.
스프링 프레임워크를 사용하면 이 Client 가 하는 것을 대신 해준다!
의존 관계가 생기는 경우들
- 클래스 또는 인터페이스의 레퍼런스 변수 사용
- 클래스의 인스턴스를 생성
- 클래스 또는 인터페이스를 상속
의존 주입 패턴이 주는 궁극적인 장점
어떤 클래스의 인스턴스를 사용할지
코드 수정 없이, 실행 시점(Runtime)에 지정할 수 있다.
반응형
'백엔드 데브코스' 카테고리의 다른 글
[Java] SOLID란? (1) - 객체 지향 프로그래밍의 5가지 기본 원칙 (0) | 2023.09.27 |
---|---|
[Java] 의존성을 주입해주는 주체 - jar, @Profile, @Order (0) | 2023.09.27 |
[Java] 의존 역전 (0) | 2023.09.26 |
[Java] 의존 관계란? (0) | 2023.09.26 |
[Java] stream API 와 Optional (0) | 2023.09.26 |