Spring Boot에서 Bean Scope는 객체의 생명 주기와 생성 방식을 결정하는 중요한 요소입니다.

이를 적절히 설정하면 성능과 메모리 사용을 최적화할 수 있습니다.

1. Bean Scope란?

Bean Scope는 Spring 컨테이너가 관리하는 Bean이 언제 생성되고, 어떻게 공유되며, 언제 소멸되는지를 정의하는 개념입니다. 기본적으로 Spring은 모든 Bean을 Singleton으로 생성하지만, 필요에 따라 다른 Scope를 설정할 수 있습니다.

2. Spring Boot에서 지원하는 Bean Scope 종류

2.1 Singleton (기본값)

  • 한 개의 Bean 인스턴스를 생성하여 애플리케이션 전역에서 공유
  • 메모리 절약성능 최적화에 유리하지만, 상태를 변경하면 모든 곳에서 공유됨

설정 방법

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

@Component
@Scope("singleton") // 생략 가능 (기본값)
public class SingletonBean {
    public SingletonBean() {
        System.out.println("Singleton Bean 생성됨");
    }
}

2.2 Prototype

  • 매번 새로운 Bean 인스턴스를 생성
  • 상태를 가지는 Bean이나 멀티스레드 환경에서 유용하지만, 메모리 사용량 증가 가능

설정 방법

@Component
@Scope("prototype")
public class PrototypeBean {
    public PrototypeBean() {
        System.out.println("Prototype Bean 생성됨");
    }
}

2.3 Request (웹 애플리케이션 전용)

  • HTTP 요청마다 새로운 Bean 인스턴스 생성
  • Spring MVC에서 요청 범위의 데이터를 처리할 때 유용

설정 방법

@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestBean {
    public RequestBean() {
        System.out.println("Request Bean 생성됨");
    }
}

2.4 Session (웹 애플리케이션 전용)

  • 사용자의 세션이 유지되는 동안 같은 Bean을 공유
  • 로그인 정보 또는 사용자 세션 정보를 저장할 때 유용

설정 방법

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionBean {
    public SessionBean() {
        System.out.println("Session Bean 생성됨");
    }
}

2.5 Application (웹 애플리케이션 전용)

  • 애플리케이션 실행 동안 단 하나의 Bean을 공유
  • 글로벌 설정 정보를 유지할 때 유용

설정 방법

@Component
@Scope(value = "application", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ApplicationBean {
    public ApplicationBean() {
        System.out.println("Application Bean 생성됨");
    }
}

3. Bean Scope 설정이 미치는 영향

Scope 생성 시점 공유 범위 주요 사용 예
Singleton 애플리케이션 시작 시 1회 애플리케이션 전체 공용 서비스, 설정 정보
Prototype 매번 새로 생성 공유 없음 상태를 가지는 객체
Request HTTP 요청 시 생성 요청 범위 요청별 사용자 정보
Session 세션 시작 시 생성 세션 범위 로그인 정보 관리
Application 애플리케이션 시작 시 1회 애플리케이션 전체 글로벌 설정 정보

4. 정리

Spring Boot에서 Bean Scope는 애플리케이션의 성능과 메모리 관리에 중요한 영향을 줍니다. 기본적으로 Singleton을 사용하지만, 필요에 따라 Prototype, Request, Session, Application 범위를 적절히 활용하여 최적의 구조를 설계하는 것이 중요합니다.

+ Recent posts