✏️ [Spring] Bean 생명주기

박상민·2025년 4월 23일

Spring

목록 보기
10/12

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 / DisposableBeanSpring에 강하게 의존간단한 내부 Bean에 적용
@Bean(initMethod, destroyMethod)느슨한 결합외부 라이브러리나 POJO 초기화/정리에 적합

주의할 점

  • @PostConstruct, @PreDestroyjavax.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

0개의 댓글