Spring Bean의 생명주기

Kim jisu·2025년 4월 28일

spring

목록 보기
5/5

Spring에서 Bean은 컨테이너에 의해 생성되고 관리되며, 특정 생명주기(Lifecycle)를 따릅니다. Bean의 생명주기를 이해하면 초기화, 자원 해제, 의존성 주입 등의 시점을 명확하게 제어할 수 있습니다.


✅ Spring Bean 생명주기 단계 요약

  1. 객체 생성 (Constructor 호출)
  2. 의존성 주입 (@Autowired, @Value 등)
  3. BeanNameAware, BeanFactoryAware 등 Aware 인터페이스 호출
  4. @PostConstruct 또는 InitializingBean의 afterPropertiesSet() → 초기화 로직
  5. Bean 사용 가능
  6. @PreDestroy 또는 DisposableBean의 destroy() → 소멸 직전 정리 작업

🔹 Bean 생명주기 메서드 제어 방법

1. @PostConstruct, @PreDestroy (가장 일반적)

@Component
public class MyBean {
    @PostConstruct
    public void init() {
        // 초기화 로직
    }

    @PreDestroy
    public void cleanup() {
        // 종료 전 정리 작업
    }
}

2. InitializingBean / DisposableBean 인터페이스 구현

public class MyBean implements InitializingBean, DisposableBean {
    @Override
    public void afterPropertiesSet() {
        // 초기화 로직
    }

    @Override
    public void destroy() {
        // 정리 작업
    }
}

3. @Bean 등록 시 initMethod / destroyMethod 지정

@Configuration
public class AppConfig {
    @Bean(initMethod = "init", destroyMethod = "close")
    public MyBean myBean() {
        return new MyBean();
    }
}

🛠️ 추가적으로 활용되는 인터페이스

  • BeanNameAware: 자신의 Bean 이름 획득
  • BeanFactoryAware: BeanFactory 획득
  • ApplicationContextAware: ApplicationContext 획득

이러한 인터페이스들은 스프링 내부의 정보를 사용하고자 할 때 유용합니다.


✅ 요약

Spring Bean은 생성 → 의존성 주입 → 초기화 → 사용 → 소멸 단계로 관리되며,
@PostConstruct, @PreDestroy, 인터페이스, initMethod 등을 통해 라이프사이클의 각 단계를 제어할 수 있습니다.

profile
Dreamer

0개의 댓글