반응형
의존 주입 패턴이란?
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)에 지정할 수 있다.
반응형
'Spring' 카테고리의 다른 글
Spring 프로젝트에 로컬 캐시를 도입해보자. (26) | 2024.01.12 |
---|---|
[Spring] 의존성을 주입해주는 주체 - jar, @Profile, @Order (0) | 2023.09.27 |
[Spring] 의존 역전에 대해 알아보자. (0) | 2023.09.26 |
[Spring] getter, setter, 생성자로 알아보는 객체지향적인 코드에 대하여 (0) | 2023.09.25 |
[백엔드] 스프링 핵심 원리 기본편 정리 (0) | 2023.04.27 |