Java/Spring

[Spring Boot] 의존성 주입(DI)

댕주 2025. 3. 16. 23:26
✏️ 한 줄 정리
생성자 주입을 사용하자

Spring Boot에서 의존성 주입(Dependency Injection, DI) 방식에는

생성자 주입, 필드 주입, 세터 주입이 있다.

 

1. 생성자 주입 (Constructor Injection)

가장 권장
@Component
public class ExampleService {
    private final ExampleRepository exampleRepository;

    @Autowired // 최신 Spring 버전에서는 생략 가능
    public ExampleService(ExampleRepository exampleRepository) {
        this.exampleRepository = exampleRepository;
    }
}

 

불변성 유지 - 객체가 생성될 때 한 번만 의존성이 설정됨

순환 참조 방지 - Spring이 순환 참조를 감지하고 컴파일 시 오류 발생

테스트 용이 - 명확한 의존성 주입으로 Mock 객체 사용이 쉬움

 

2. 필드 주입 (Field Injection)

권장되지 않음
@Component
public class ExampleService {
    @Autowired
    private ExampleRepository exampleRepository;
}

테스트 어려움 - Reflection을 사용하여 주입되므로 Mock 객체 설정이 복잡함

의존성 불분명 - 객체를 생성할 때 어떤 의존성이 필요한지 명확하지 않음

불변성 깨짐 - 필드를 변경할 수 있어 예기치 않은 변경 발생 가능

 

3. 세터 주입 (Setter Injection)

특정 경우에만 사용 (설정 값 변경)
@Component
public class ExampleService {
    private ExampleRepository exampleRepository;

    @Autowired
    public void setExampleRepository(ExampleRepository exampleRepository) {
        this.exampleRepository = exampleRepository;
    }
}

✅ 필요한 경우 유연하게 변경 가능

강제성 부족 - 의존성이 설정되지 않은 상태에서도 객체가 생성될 수 있음

불필요한 수정 위험 - 코드 유지보수가 어려워 질 수 있음

'Java > Spring' 카테고리의 다른 글

[Spring] 프록시 패턴(Proxy Pattern)  (0) 2025.03.17
[Spring] 트랜잭션  (0) 2025.03.16