ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Springboot -DI, IoC, Bean ...
    SpringBoot 2021. 10. 4. 16:51

    # Spring IoC(Inversion of control)

    • DL(Dependency Lookup: 의존성 탐색) + DI(Dependency Injection: 의존성 주입)
    • 제어의 역전: 객체의 생성부터 생명주기 전체를 개발자가 아닌 특정 컨테이너가 도맡아 제어권이 컨테이너로 넘어가게 되는 개념
    • Bean: IoC컨테이너에서 관리하는 자바 객체(POJO: Plain Old Java Object)
      • 각 bean은 singleton 방식으로 생성된다.
    • IoC 컨테이너(=DI 컨테이너): 객체를 생성, 관리하는 객체로 bean형태로 객체를 관리한다.
    • IoC 컨테이너에 bean을 등록하는 방법
      1. @Component 또는 @Component를 사용하는 다른 어노테이션(@Controller 등)이용
        • 해당 어노테이션들을 이용하여 클래스를 생성하면 @SpringBootApplication의 @ComponentScan을 통해 등록
        • 개발자가 직접 제어할 수 없는 외부 라이브러리를 활용하는 경우 or 초기 설정을 위한 경우
      2. Bean 설정 파일에 직접 bean을 등록
        • @Configuration이 선언된 클래스 내에서 @Bean을 선언하여 등록한다.
        • 개발자가 직접 개발한 클래스를 bean으로 등록하는 경우
      3. @Component와 @Bean 어노테이션은 각자 선언할 수 있는 타입이 정해져있다.
        • 해당 용도 외에 사용할 경우 컴파일 에러가 발생.

    # Spring DI(Dependency Injection)

    • 개발자의 소스 코드가 아닌 외부의 설정 파일 등을 통해 구성 요소 간 의존 관계를 정의하는 디자인 패턴
      • Java DI: A 클래스에서 B, C 객체를 직접 생성하여 사용
      • Spring DI: A 클래스에서 B, C객체를 사용하기 위해 IoC컨테이너가 외부에 생성된 객체를 통해 A에 의존성을 주입
    • 장점: 유지보수가 용이하고, 모듈 간 결합도가 낮아진다.
    • DI(의존성 주입) 방법
      • Constructor(생성자)를 통한 주입이 권장된다.
      • ⇒ 필수 의존성 없이는 인스턴스 생성이 불가능하도록 강제할 수 있으므로
      1. Field Injection
      @Component
      public class SampleController {
          @Autowired
          private SampleRepository sampleRepository;
      }​

      1. Setter Injection
      @Component
      public class SampleController {
          private SampleRepository sampleRepository;
       
          @Autowired
          public void setSampleRepository(SampleRepository sampleRepository) {
              this.sampleRepository = sampleRepository;
          }
      }​

      1. Constructor Injection
      @Component
      public class SampleController {
          private SampleRepository sampleRepository;
       
          @Autowired
          public SampleController(SampleRepository sampleRepository) {
              this.sampleRepository = sampleRepository;
          }
      }​

    'SpringBoot' 카테고리의 다른 글

    Springboot -동작원리  (0) 2021.10.04
    Springboot -@SpringBootApplication  (0) 2021.10.04
Designed by Tistory.