스프링 빈 생명주기 심층 분석

스프링 IoC 컨테이너와 빈 관리

스프링 프레임워크의 핵심인 IoC(제어 역전) 컨테이너는 애플리케이션 객체(빈)의 생성, 구성, 관리를 담당합니다. 빈의 생성부터 소멸까지의 전 과정을 이해하는 것은 효율적이고 유지보수 가능한 스프링 애플리케이션 개발에 필수적입니다.

빈 생명주기 주요 단계

  1. 인스턴스 생성 및 의존성 주입: 리플렉션을 통한 객체 생성과 의존성 해결
  2. 초기화 및 소멸 처리: 사용 전 초기화 로직 실행과 컨테이너 종료 시 정리 작업

컨테이너 정보 인식을 위한 Aware 인터페이스

  • BeanNameAware: setBeanName() - 빈 이름 인식
  • BeanFactoryAware: setBeanFactory() - BeanFactory 참조 획득
  • ApplicationContextAware: setApplicationContext() - 애플리케이션 컨텍스트 접근

초기화 처리 메커니즘

@Component
public class DataService {
    @PostConstruct
    public void prepareResources() {
        // 초기화 작업
    }
}
@Component
public class NetworkManager implements InitializingBean {
    @Override
    public void afterPropertiesSet() {
        // 연결 설정
    }
}
@Configuration
public class AppSetup {
    @Bean(initMethod = "setupConnection")
    public ExternalService externalService() {
        return new ExternalService();
    }
}

public class ExternalService {
    public void setupConnection() {
        // 외부 서비스 초기화
    }
}

소멸 단계 처리 방법

  • @PreDestroy: 표준 애너테이션 기반 정리
  • DisposableBean: destroy() 구현 (스프링 결합)
  • destroy-method: 외부 라이브러리 통합용

BeanPostProcessor의 역할

빈 생성 과정에서 개입하는 확장 포인트:

  • postProcessBeforeInitialization(): 초기화 전 처리
  • postProcessAfterInitialization(): 초기화 후 처리(AOP 프록시 생성 등)

빈 생명주기 전체 흐름

순서단계설명
1인스턴스화생성자 호출
2의존성 주입필드/생성자 주입
3Aware 인터페이스컨테이너 정보 전달
4BeanPostProcessor(전)초기화 전 가공
5초기화@PostConstruct → InitializingBean → init-method
6BeanPostProcessor(후)초기화 후 가공
7사용 가능애플리케이션에서 활용
8소멸@PreDestroy → DisposableBean → destroy-method

실무 적용 가이드라인

  • 표준 애너테이션 @PostConstruct/@PreDestroy 우선 사용
  • 서드파티 클래스는 init-method/destroy-method 활용
  • Spring 인터페이스 직접 구현은 결합도 증가로 권장하지 않음

태그: 스프링 프레임워크 IoC 컨테이너 빈 생명주기 BeanPostProcessor 의존성 주입

7월 12일 04:01에 게시됨