스프링 컨테이너는 Bean을 등록할 때 다음과 같은 순서로 생명주기를 관리한다.
생성자 호출 → 의존성 주입 → 초기화 콜백 → 사용 → 소멸 콜백
Spring이 제공하는 다양한 방법을 통해 이 생명주기 단계마다 로직을 삽입할 수 있다.
2-1. 기본 설정
@Configuration
@ComponentScan(basePackages = "com.example.lifecycle")
public class AppConfig {
}
2-2. 생명주기 메서드를 정의한 Bean
@Component
public class LifeCycleBean {
public LifeCycleBean() {
System.out.println("1. 생성자 호출");
}
@PostConstruct
public void init() {
System.out.println("2. 초기화 메서드 실행 (@PostConstruct)");
}
@PreDestroy
public void destroy() {
System.out.println("4. 소멸 메서드 실행 (@PreDestroy)");
}
}
3. 실행 결과
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
LifeCycleBean bean = context.getBean(LifeCycleBean.class);
System.out.println("3. Bean 사용 중...");
context.close(); // @PreDestroy 호출됨
}
}
출력 결과
1. 생성자 호출
2. 초기화 메서드 실행 (@PostConstruct)
4. Bean 사용 중...
3. 소멸 메서드 실행 (@PreDestroy)
@Component
public class CustomLifeCycleBean implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() {
System.out.println("초기화 (InitializingBean.afterPropertiesSet)");
}
@Override
public void destroy() {
System.out.println("소멸 (DisposableBean.destroy)");
}
}
afterPropertiesSet()
destroy()
context.close())✅ 특징
@Configuration
public class ConfigWithBeanMethod {
@Bean(initMethod = "init", destroyMethod = "cleanup")
public CustomBean customBean() {
return new CustomBean();
}
}
public class CustomBean {
public void init() {
System.out.println("초기화 (initMethod)");
}
public void cleanup() {
System.out.println("소멸 (destroyMethod)");
}
}
init()
initMethod="init"cleanup()
destroyMethod="cleanup"✅ 특징
✅ 비교 요약
| 방식 | 결합도 | 사용 용도 |
|---|---|---|
InitializingBean / DisposableBean | Spring에 강하게 의존 | 간단한 내부 Bean에 적용 |
@Bean(initMethod, destroyMethod) | 느슨한 결합 | 외부 라이브러리나 POJO 초기화/정리에 적합 |
주의할 점
@PostConstruct, @PreDestroy는 javax.annotation 또는 jakarta.annotation 패키지에서 제공되므로 JDK 9 이상에서는 별도 의존성이 필요Spring Bean 생명주기를 명확히 이해하면 다음과 같은 상황에 유용하다:
초기화/소멸 메서드가 필요한 경우, 가급적 @PostConstruct, @PreDestroy 또는 @Bean(initMethod, destroyMethod) 방식처럼 느슨하게 결합된 구조를 사용하는 것이 유지보수에 유리하다.
출처
https://docs.spring.io/spring-framework/reference/core/beans/definition.html