Skip to Content
Suffering builds character

6.의존성 주입

1. DI, Dependency Injection

Dependency injection (DI) is a process whereby objects define their dependencies (that is, the other objects with which they work) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies on its own by using direct construction of classes or the Service Locator pattern.

→ 의존성 주입이란, Spring Container 에서 관리되는 의존성(bean)을 비즈니스 객체에 주입(초기화)시켜주는 과정

2. 의존성 주입 방식

의존성을 주입하는 방법은 크게 4가지(Field, setter, constructor, factory)로 나뉘며, 기본적으로 Java 객체 지향 문법에서 필드에 값을 초기화 하는 방법을 기반으로 구분된 것

3. Java에서 필드의 값을 초기화 하는 방법

3-1. Field를 통해 직접 초기화

필드에 직접 할당하는 방식을 통해 필드의 값을 초기화 할 수 있음

Mouse.java
class Mouse { int age = 5; // 필드에 직접 초기화 }
Main.java
Mouse mini = new Mouse(); mini.age = 10; // 필드에 직접 초기화

3-2. 생성자 메서드의 인수를 통해 초기화, Constructor(value)

생성자 메서드를 통해 인스턴스를 생성하는 과정에서 필드의 값을 초기화할 수 있음

Main.java
Mouse mini = new Mouse("mini", 5);

3-3. Setter 메서드를 통해 초기화, Setter(value)

SetXxx()와 같은 Setter 메서드를 통해 필드의 값을 초기화 할 수 있음

Main.java
Mouse mini = new Mouse("mini", 5); mini.setCountry("하와이");

4. Spring Container의 의존성 주입 방식

스프링 역시 Java 객체 지향 문법을 기반으로 필드의 값을 초기화 하는 방법을 통해 의존성을 주입받을 수 있도록 방식을 제공하고 있음

  1. Field 기반 주입
  2. 생성자 기반 주입
  3. Setter 기반 주입
  4. 커스텀 메서드(Factory) 기반 주입

3. Spring에서 권장하는 의존성 주입 방식

_The Spring team generally advocates constructor injection,** as it lets you implement application components as immutable objects and ensures that required dependencies are not null.** Furthermore, constructor-injected components are always returned to the client (calling) code in a fully initialized state._

→ 스프링에서는 생성자 기반의 의존성 주입 방식을 권장하며, 이유는 다음과 같음

3-1. 불변성, Immutable

“lets you implement application components as immutable objects”

적용 방법
→ 의존성을 주입받을 필드에 final 키워드를 지정하여 생성자 메서드의 작성이 강제되도록 구현

3-2. 객체 생성 과정에서 의존성을 빠뜨릴 확률이 줄어듦

“ensures that required dependencies are not null”

의존성 해결 프로세스

Last updated on