✏️ [Spring] Bean 생명주기

2026. 8. 1. 00:22·Backend/Spring

이 글은 Velog에서 이전한 글입니다. Velog 원문 보기

Bean 생명주기란?

스프링 컨테이너는 Bean을 등록할 때 다음과 같은 순서로 생명주기를 관리한다.

생성자 호출 → 의존성 주입 → 초기화 콜백 → 사용 → 소멸 콜백

Spring이 제공하는 다양한 방법을 통해 이 생명주기 단계마다 로직을 삽입할 수 있다.

예제 코드로 알아보는 Bean 생명주기

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)

생명주기 커스터마이징 방법

InitializingBean, DisposableBean 방식 설명

@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()

  • 시점: 의존성 주입 완료 후
  • 역할: 초기화 작업 (DB 연결, 캐시 로딩 등)

destroy()

  • 시점: 컨테이너 종료 시점 (context.close())
  • 역할: 리소스 정리, 연결 해제

✅ 특징

  • Spring 인터페이스에 강하게 결합됨
  • 테스트나 재사용에 불리할 수 있음

@Bean(initMethod, destroyMethod) 방식 설명

@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"
  • 설명: Bean 생성 후 호출됨

cleanup()

  • 지정 방법: destroyMethod="cleanup"
  • 설명: 컨테이너 종료 시 호출됨

✅ 특징

  • POJO 객체(Spring과 무관한 일반 클래스)에도 적용 가능 -> 느슨한 결합
  • 테스트 용이성과 코드 재사용성 높음

✅ 비교 요약

방식 결합도 사용 용도
InitializingBean / DisposableBean Spring에 강하게 의존 간단한 내부 Bean에 적용
@Bean(initMethod, destroyMethod) 느슨한 결합 외부 라이브러리나 POJO 초기화/정리에 적합

주의할 점

  • @PostConstruct, @PreDestroy는 javax.annotation 또는 jakarta.annotation 패키지에서 제공되므로 JDK 9 이상에서는 별도 의존성이 필요
  • InitializingBean, DisposableBean은 강하게 결합되므로 가급적 애노테이션 방식 권장

📝 마무리

Spring Bean 생명주기를 명확히 이해하면 다음과 같은 상황에 유용하다:

  • 외부 리소스(DB, Socket 등) 초기화/정리 필요할 때
  • 공통 초기화/종료 로직이 필요한 경우
  • 객체 수명 관리가 중요한 서비스에서 메모리 누수 방지

초기화/소멸 메서드가 필요한 경우, 가급적 @PostConstruct, @PreDestroy 또는 @Bean(initMethod, destroyMethod) 방식처럼 느슨하게 결합된 구조를 사용하는 것이 유지보수에 유리하다.


출처
https://docs.spring.io/spring-framework/reference/core/beans/definition.html

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

[Spring] Spring Batch: 대용량 배치 처리의 핵심 프레임워크  (0) 2026.08.02
[Spring] Filter & Interceptor  (0) 2026.08.01
[Spring] 역할과 구현의 분리, 스프링 컨테이너의 필요성  (0) 2026.07.31
✏️ [Spring] Spring Security Testing  (0) 2026.07.31
✏️ [Spring] AOP(Aspect Oriented Programming)란?  (0) 2026.07.28
'Backend/Spring' 카테고리의 다른 글
  • [Spring] Spring Batch: 대용량 배치 처리의 핵심 프레임워크
  • [Spring] Filter & Interceptor
  • [Spring] 역할과 구현의 분리, 스프링 컨테이너의 필요성
  • ✏️ [Spring] Spring Security Testing
pp8817
pp8817
공부한 내용, 개발 관련 지식, 트러블 슈팅 등을 기록합니다. 이전 블로그: https://velog.io/@pp8817/posts
  • pp8817
    끄적이는 개발 log
    pp8817
  • 전체
    오늘
    어제
    • 분류 전체보기 (273)
      • Project (71)
        • 척척학사 (29)
        • Book (23)
        • Saynow (3)
        • YAPP 27기 (4)
        • 나의 작은 프로젝트 (10)
        • Landit (2)
      • Backend (88)
        • Spring (13)
        • Spring MVC (13)
        • Spring Security (4)
        • JPA (26)
        • Database (19)
        • HTTP·Web (13)
        • Architecture (0)
      • Language·CS (59)
        • Java·Kotlin (5)
        • CS Interview (17)
        • Backend Interview (5)
        • Concepts (32)
      • Algorithm (25)
        • Algorithm (24)
        • 소마 알고리즘 스터디 (1)
      • Infra (8)
      • Troubleshooting (11)
      • Retrospective (6)
      • Etc (5)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    척척학사
    Book
    CS Interview
    Python
    Algorithm
    object
    Spring
    java
    HTTP WEB 기본 지식
    게시판
    jpa
    BOJ
    http
    트러블슈팅
    나의 작은 프로젝트
    Project
    interview
    OS
    개념 정리!
    Spring MVC
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
pp8817
✏️ [Spring] Bean 생명주기
상단으로

티스토리툴바