Spring Boot

Spring Boot에서 의존성 주입(Dependency Injection)을 사용하는 방법

Pro.Dev 2025. 1. 8. 14:49
반응형

Spring Boot에서 의존성 주입(Dependency Injection)을 사용하는 방법

Spring Boot에서 의존성 주입(Dependency Injection, DI)은 애플리케이션의 구성 요소 간의 결합도를 낮추고 유연성과 재사용성을 높이는 중요한 설계 패턴입니다. Spring 프레임워크는 DI를 통해 객체 간의 의존성을 관리하며, 애플리케이션 개발을 효율적으로 지원합니다. 이 글에서는 DI의 개념과 Spring Boot에서 사용하는 방법을 설명합니다.


1. 의존성 주입(Dependency Injection)이란?

의존성 주입은 객체가 필요한 의존성을 스스로 생성하지 않고, 외부에서 제공받는 설계 방식입니다. 이를 통해 코드의 결합도를 낮추고, 테스트 및 유지보수를 용이하게 만듭니다.

전통적인 방식:

public class Car {
    private Engine engine;

    public Car() {
        this.engine = new Engine();
    }
}

의존성 주입 방식:

public class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }
}

2. Spring Boot에서 의존성 주입의 주요 방식

Spring Boot는 다음 세 가지 방식으로 의존성을 주입할 수 있습니다:

  1. 생성자 주입(Constructor Injection)
  2. 세터 주입(Setter Injection)
  3. 필드 주입(Field Injection)

3. 의존성 주입 방법

1) 생성자 주입 (추천)

생성자 주입은 의존성을 생성자를 통해 주입하는 방식입니다. Spring Boot에서는 이 방식이 가장 권장됩니다.

예제:

import org.springframework.stereotype.Component;

@Component
public class Engine {
    public String start() {
        return "Engine started!";
    }
}

import org.springframework.stereotype.Component;

@Component
public class Car {
    private final Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public String drive() {
        return engine.start() + " Car is driving.";
    }
}
2) 세터 주입

세터 메서드를 사용해 의존성을 주입합니다. 선택적 의존성을 주입할 때 적합합니다.

예제:

import org.springframework.stereotype.Component;

@Component
public class Car {
    private Engine engine;

    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    public String drive() {
        return engine.start() + " Car is driving.";
    }
}
3) 필드 주입

필드에 직접 의존성을 주입합니다. 간결하지만, 테스트가 어려워지는 단점이 있습니다.

예제:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Car {

    @Autowired
    private Engine engine;

    public String drive() {
        return engine.start() + " Car is driving.";
    }
}

4. @Component와 @Autowired

  1. @Component

    • Spring이 관리하는 빈(Bean)을 생성하는 어노테이션입니다.
    • 클래스에 @Component를 추가하면 Spring 컨테이너가 해당 클래스를 빈으로 등록합니다.
  2. @Autowired

    • Spring이 빈을 자동으로 주입하도록 지시하는 어노테이션입니다.
    • 생성자, 세터, 필드 어디에서나 사용할 수 있습니다.

예제:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Car {
    private final Engine engine;

    @Autowired
    public Car(Engine engine) {
        this.engine = engine;
    }

    public String drive() {
        return engine.start() + " Car is driving.";
    }
}

5. 스코프와 의존성 관리

Spring Boot에서는 빈의 스코프(Scope)를 설정하여 객체의 생명주기를 관리할 수 있습니다. 기본 스코프는 싱글톤(Singleton)입니다.

  1. 싱글톤 스코프 (Singleton)

    • 애플리케이션 전체에서 하나의 인스턴스만 생성됩니다.
  2. 프로토타입 스코프 (Prototype)

    • 요청할 때마다 새로운 인스턴스가 생성됩니다.

예제:

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class Engine {
    public String start() {
        return "Prototype Engine started!";
    }
}

6. 테스트 코드 작성

Spring Boot에서는 의존성 주입을 활용하여 간단하게 테스트를 작성할 수 있습니다.

테스트 예제:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
public class CarTest {

    @Autowired
    private Car car;

    @Test
    public void testCarDrive() {
        String result = car.drive();
        assertEquals("Engine started! Car is driving.", result);
    }
}

반응형