[내배캠/TIL(6/3)]Spring 심화반-DI, IoC 컨테이너

손홍서·2022년 6월 3일
0

Spring

목록 보기
6/24
post-thumbnail

day31 TIL

DI(의존성 주입)

public class ProductService {
    // 멤버 변수 선언
    private final ProductRepository productRepository;

    // 생성자: ProductService() 가 생성될 때 호출됨
    public ProductService(String dbId,String dbPassword) {
        // 멤버 변수 생성
        this.productRepository = new ProductRepository(dbId, dbPassword);
    }
}

Service가 생성될 때마다 Repository를 함께 생성해서 Service 개수만큼 Repository 개수 증가
->
이건 쫌....
결합도 너무 높아 유연한 코드 작성이 힘들다.
한 클래스를 수정하면 우르르 다른 코드들도 수정해야한다.

그래서 사용하는 것이 의존성 주입!

하나의 객체에서 다른 객체가 필요할 때, 객체를 직접 생성하지 않고, 이미 생성되어 있는 객체를 가져오는 작업을 DI (Dependency Injection) 혹은 한국말로 의존성 주입이라고 부른다.

public class ProductService {
    // 멤버 변수 선언
    private final ProductRepository productRepository;

    // 생성자: ProductService() 가 생성될 때 호출됨
    public ProductService(ProductRepository productRepository) {
        // 멤버 변수 생성
        this.productRepository = productRepository;
    }
}

이렇게 미리 생성되어 있는 객체 자체를 가져와서 사용한다.
그러면 변화가 생겨도 변화가 필요한 하나의 클래스만 수정하면 된다.
이러한 부분은 프로그램의 제어 프름이 뒤바뀐다고하여 제어의 역전(IoC: Inversion of Control)이라고 부른다. 보통은 사용자가 자신이 필요한 객체를 생성해 사용한느 것이 일반적이지만 객체를 요청하면 어디서 어떻게 만들어진지 모르는 객체를 사용하는 것이기 떄문이다.

스프링 IoC 컨테이너

IoC 컨테이너는 DI를 사용하기 위한 객체를 생성해 관리하는 역할을 한다.

  • 빈 (Bean): 스프링이 생성해주는 객체
  • 스프링 IoC 컨테이너: 빈을 모아둔 통

@Controller, @RestController, @Service, @Repository 와 같이 앞에 '@' 를 붙이는 것을 어노테이션 (Annotation) 이라고 부르고, 모두 스프링의 빈으로 등록되지만, 좀 더 특별한 역할을 맡은 빈들이다.

profile
Hello World!!

0개의 댓글