-
DI(Dependency Injection)Spring&Spring Boot Story 2023. 1. 30. 17:44
DI(Dependency Injection) : 의존성 주입(의존 관계 주입)
- 제어 역전의 방법 중 하나로, 사용할 객체를 직접 생성하지 않고 외부 컨테이너가 생성한 객체를 주입받아 사용하는 방식을 의미(외부에서 미리 생성해두고 필요한 곳에 할당(주입))

- 스프링에서는 외부에서 객체를 생성하면 IoC 컨테이너라는 곳에 담는데, IoC 컨테이너 안에 저장된 객체를 Bean이라고 함
- 스프링에서 의존성을 주입받는 방법은 3가지가 있음
- 필드 객체 선언을 통한 의존성 주입(Field Injection)
- setter 메서드를 통한 의존성 주입(Setter Injection)
- 생성자를 통한 의존성 주입(Constructor Injection)
- 스프링에서는 @Autowired 라는 어노테이션(annotation)을 통해 의존성을 주입할 수 있음. 스프링 4.3 이후 버전은 생성자를 통해 의존성을 주입할 때 @Autowired 어노테이션을 생략가능
1. 필드 객체 선언을 통한 의존성 주입(Field Injection)
@RestController public class FieldInjectionController { @Autowired private Myservice myService; }2. setter 메서드를 통한 의존성 주입(Setter Injection)
@RestController public class SetterInjectionController { Myservice myService; @Autowired public void setMyService(MyService myService) { this.myService = myService; } }3. 생성자를 통한 의존성 주입(Constructor Injection)
@RestController public class DIController { MyService myService; @Autowired public DIController(MyService myService) { this.myService = myService; } @GetMapping("/di/hello") public String getHello() { return myService.getHello(); } }- 스프링 공식 문서에서 권장하는 의존성 주입 방법은 생성자를 통해 의존성을 주입받는 방식
-> 다른 방식과는 다르게 생성자를 통해 의존성을 주입받는 방식은 레퍼런스 객체 없이는 객체를 초기화할 수 없게 설계할 수 있기 때문
'Spring&Spring Boot Story' 카테고리의 다른 글
Maven & Gradle (0) 2023.05.14 JUnit (0) 2023.05.14 SLF4J (0) 2023.05.13 Controller (0) 2023.05.13 Spring과 Spring Boot의 차이 (0) 2023.01.30