라이프 사이클 직접 확인하기

우리는 빈의 라이프 사이클에 대해서 읽었는데, 이제 라이프 사이클을 직접 확인해 보자.

HelloWorld 클래스에서 Spring Framework의 다음 인터페이스들을 구현하자.

  • ApplicationContextAware : setApplicationContext 메서드를 구현해야 한다.
  • BeanNameAware : setBeanName 메서드를 구현해야 한다.
  • InitializingBean : afterPropertiesSet 메서드를 구현해야 한다.
  • BeanFactoryAware : setBeanFactory 메서드를 구현해야 한다.
  • BeanPostProcessor : postPorcessBeforeInitialization과 postProcessAfterInitialization 메서드를 구현해야 한다.
  • DisposableBean : destroy 메서드를 구현해야 한다.

모든 메서드에 System.out.println을 추가하자. 일단 다음 두 메서드를 추가하자.

public void myInit() {
       System.out.println("custom myInit is called ");
}
     public void myDestroy() {
       System.out.println("custom myDestroy is called ");
}

빈 정의에 init-method와 destroy-method를 다음과 같이 수정한다.

<bean id="helloWorld" class="com.packt.lifecycle.HelloWorld"
       init-method="myInit" destroy-method="myDestroy">
       <property name="message" value="Welcome to the Spring world">
       </property>
</bean>

HelloWorldExample을 다음처럼 수정하면 셧다운 후크가 등록되서 어플리케이션 컨텍스트가 destory 되도록 할 수 있다.

AbstractApplicationContext context = new  ClassPathXmlApplicationConte
   xt("applicationContext.xml");
     HelloWorld world = (HelloWorld) context.getBean("helloWorld");
     System.out.println(world.getMessage());
     context.registerShutdownHook();

어플리케이션을 실행하면 다음 내용이 출력된다.

setBeanName is called with helloWorld
setBeanFactory is called
setApplicationContext is called
afterPropertiesSet is called
custom myInit is called
Welcome to the Spring world
destroy is called
custom myDestroy is called

setBeanName, setBeanFactory, setApplicationContext, afterPropertiesSet 순서대로 호출되고 커스텀 init 메서드가 호출되는 것을 보여준다. 프로그램 종료 처리중에는 destory 메서드가 처음 호출되고 다음에 커스텀 destory-method가 호출된다.