더북(TheBook)

예제 4-20 자동으로 셧다운 후크를 생성해서 등록하는 빈([[application-context-aware]] ShutdownHookBean.java)

package com.apress.prospring5.ch4;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.GenericApplicationContext;

public class ShutdownHookBean implements ApplicationContextAware {
    private ApplicationContext ctx;

    /** @Implements {@link ApplicationContextAware
        #setApplicationContext(ApplicationContext)} }*/
    public void setApplicationContext(ApplicationContext ctx)
        throws BeansException {

        if (ctx instanceof GenericApplicationContext) {
            ((GenericApplicationContext) ctx).registerShutdownHook();
        }
    }
}

 

이제 이 예제 코드는 대부분 익숙할 것입니다. ApplicationContextAware 인터페이스는 setApplicationContext(ApplicationContext) 메서드를 정의하며, 스프링은 이 메서드를 호출해 ApplicationContext의 참조를 전달합니다. 앞 예제에서는 ShutdownHookBean 클래스에서 스프링이 전달한 ApplicationContextGenericApplicationContext 타입인지 확인해서 registerShutdownHook() 메서드를 호출할 수 있는지 점검했습니다. 전달된 ApplicationContextGenericApplicationContext라면 ApplicationContext에 셧다운 후크를 등록합니다. 다음은 이 빈이 DestructiveBeanWithInterface 빈과 작동하도록 하는 구성 내용입니다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.