본문 바로가기

스프링

Spring Bean 라이프사이클

Spring Bean 라이프사이클이란 Spring IoC 컨테이너가 Bean 객체를 생성하고, 의존성을 주입하고, 초기화한 뒤 사용하다가, 마지막에 정리하는 과정을 말한다.

기본 singleton Bean은 아래 순서로 진행된다. 다만 @Lazy, prototype scope, request scope처럼 Bean 설정에 따라 생성 시점이나 소멸 시점은 달라질 수 있다.

  1. Spring IoC 컨테이너 생성
  2. Spring Bean 생성 및 의존성 주입
  3. 초기화 메소드
  4. 사용
  5. 소멸 메소드
  6. Spring IoC 컨테이너 종료

여기서 우리는 2,3,5번을 디테일하게 확인해보자.

Spring Bean 생성 및 의존성 주입

Spring IoC 컨테이너가 생성된 후에 먼저 BeanDefinition을 등록한다. BeanDefinition이란 Bean과 관련된 메타정보라고 보면 된다. 아래와 같은 정보가 있다.

Bean 이름
Bean 클래스
Scope
생성 방식
의존성 정보
초기화 메소드
소멸 메소드

BeanDefinition을 가지고 Bean 객체를 생성한다. 생성자/필드/setter 주입으로 의존성을 주입할 수 있다.

  • 생성자 주입: Spring이 생성자에 필요한 의존 Bean을 먼저 조회한 뒤, 생성자 인자로 전달하면서 Bean 객체를 생성한다.
  • 필드/setter 주입: Bean 객체를 먼저 생성한 뒤, 필드나 setter를 통해 의존성을 주입한다.

초기화 메소드

초기화 메소드는 Bean 인스턴스 생성과 의존성 주입이 끝난 뒤, Bean이 실제로 사용되기 전에 Spring이 호출해주는 초기화 콜백이다. 크게 3가지가 있다.

  • @PostConstruct
  • InitializingBean.afterPropertiesSet()
  • Custom init-method

@PostConstruct

@Service  
class BookService {
	...
  
    @PostConstruct  
    fun postConstruct() {  
	    logger.info { "bookService:postConstruct" } 
    }  
}

InitializingBean.afterPropertiesSet()

@Service  
class BookService: InitializingBean {
	...
  
    override fun afterPropertiesSet() {  
        logger.info { "bookService:afterPropertiesSet" }  
    }  
}

Custom init-method

Custom init 메소드는 @Bean 애노테이션의 initMethod 속성으로 지정할 수 있다.

@Configuration  
class AppConfig {  
  
    @Bean(initMethod = "init")  
    fun bookService() = BookService()  
}

class BookService {  
	...
  
    fun init() {  
        logger.info { "bookService:custom-init" }  
    }  
}

세 가지 초기화 콜백을 모두 사용하면 일반적으로 @PostConstruct, InitializingBean.afterPropertiesSet(), custom init-method 순서로 호출된다.

소멸 메소드

소멸 메소드는 Spring IoC 컨테이너가 종료되는 과정에서, 관리 중인 singleton Bean을 폐기하기 직전에 호출하는 콜백이다. 초기화 메소드처럼 3가지 방식이 있다.

  • @PreDestroy
  • DisposableBean.destroy()
  • Custom destroy-method

명시적으로 테스트하고 싶으면 applicationContext를 닫아보면 된다.

@SpringBootApplication  
class SpringStudyApplication  
  
fun main(args: Array<String>) {  
    val applicationContext = runApplication<SpringStudyApplication>(*args)  
  
    applicationContext.close() // 컨테이너를 종료해 소멸 콜백을 확인한다.
}

@PreDestroy

@Service  
class BookService {
	...
  
    @PreDestroy  
    fun destroy() {  
        logger.info { "bookService:preDestroy" }  
    }  
}

DisposableBean.destroy()

@Service  
class BookService: DisposableBean {
	...
	
    override fun destroy() {  
        logger.info { "bookService:destroy" }  
    }  
}

Custom destroy-method

Custom destroy 메소드는 @Bean 애노테이션의 destroyMethod 속성으로 지정할 수 있다.

@Configuration  
class AppConfig {  
  
    @Bean(destroyMethod = "destroy")  
    fun bookService() = BookService()  
  
}

class BookService {
	...
  
    fun destroy() {  
        logger.info { "bookService:custom-destroy" }  
    }  
}

단, prototype scope Bean은 Spring이 생성, 의존성 주입, 초기화까지만 관리하고, 이후에는 컨테이너가 추적하지 않는다. 따라서 @PreDestroy, DisposableBean.destroy(), custom destroy-method 같은 소멸 콜백은 자동으로 호출되지 않는다. 필요한 경우 사용하는 쪽에서 직접 정리해야 한다.

소멸 콜백은 일반적으로 @PreDestroy가 먼저 처리되고, 이후 DisposableBean.destroy(), custom destroy-method 순서로 호출된다.

 

이렇듯 Spring IoC 컨테이너는 애플리케이션 컴포넌트의 생성, 설정, 관리를 중앙화하기 때문에 이런 라이프사이클을 표준 방식으로 지원한다.

 

ref

'스프링' 카테고리의 다른 글

Spring IoC  (0) 2026.05.16