본문 바로가기

SpringFramework Core - I. IoC 컨테이너/6. Bean 커스터마이징하기

1.6.1.6. 웹 앱이 아닐 때 스프링 IoC 컨테이너를 Gracefully하게 Shutting Down 하기

  이 부분은 웹앱이 아닌 곳에서만 적용된다. 스프링의 웹 기반 ApplicationContext 구현체는 이미 관련된 웹앱이 shut down할 때 스프링 IoC 컨테이너를 gracefully하게 shut down시키는 코드를 가지고 있다. 

 

만약 웹앱 환경이 아닌 곳에서 스프링의 IoC 컨테이너를 사용하고 있다면(예를 들어, rich client 데스크탑 환경) shutdown hook을 JVM에 등록하라. 그렇게 하면 graceful한 shutdown을 보장하며 싱글턴 bean들을 소멸시키는 관련 메소드를 호출하여 모든 리소스를 release하게 해줄 것이다. 여전히 이러한 소멸 콜백들은 정확하게 설정하고 실행해야만 한다. 

 

shutdown hook을 등록하기 위해서는, ConfigurableApplicationContext 인터페이스에 선언된 registerShutdownHook() 메소드를 다음과 같이 호출해야 한다.

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public final class Boot {

    public static void main(final String[] args) throws Exception {
        configurableApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        
        // 위의 context에 shutdown hook 추가
        ctx.registerShutdownHook();
        
        // 여기서 앱 구동...
        
        // 메인 메소드 위치, 앱이 shutting down되기 전에 hook이 호출됨...
    }
}