====== Spring Framework Bean Lifecycle ====== * [[springframework:bean|SpringFramework Bean]] * ''@PostConstruct'' * ''@PreDestroy'' * ''InitializingBean'' * ''DisposableBean'' * ''@Bean(initMethod="", destroyMethod="")'' * ''BeanNameAware'' * ''ApplicationContextAware'' ===== @PostConstruct / @PreDestroy 의존성 ===== * [[java:9|Java 9]]부터 Java EE 의존성이 deprecated 되고 Java 11 에서 빠졌기 때문에 Java 11 사용시에는 의존성에 명시를 해줘야 한다. javax.annotation javax.annotation-api 1.3.2 ===== SmartLifeCycle ===== * [[https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/SmartLifecycle.html|SmartLifecycle]] * [[http://selvakumaresra.herokuapp.com/spring-smartlifecycle-smart-shutdown-sequence-for-java-service/|Spring SmartLifeCycle]] * ''getPhase()'' 에서 ''Integer.MAX_VALUE''를 리턴하면 제일 늦게 생성되고, 제일 먼저 파괴 된다. 이 최우선 파괴 시점에 다른 Bean의 파괴 타이밍을 조정해준다. * ''SmartLifeCycle'' 안에서 다른 Bean 을 destroy 하려면, 그냥 하면 안되고 ''BeanFactoryAware'' 인터페이스를 구현하여 ''DefaultSingletonBeanRegistry'' 를 주입받은뒤, [[https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.html#destroySingleton-java.lang.String-|DefaultSingletonBeanRegistry.destroySingleton(beanName)]]을 사용해야한다. 그래야 Bean destroy 후에 해당 빈을 ApplicationContext 에서 제거해주어 중복 destroy 를 막아준다. * 입력받는 역할을 하는것(MQ Listener 등)을 먼저 종료시켜줘야 더이상 입력이 없는 상태에서 Gracefull 한 종료가 가능해진다. * [[https://www.baeldung.com/spring-boot-web-server-shutdown|Web Server Graceful Shutdown in Spring Boot | Baeldung]] ===== 참조 ===== * [[https://www.baeldung.com/spring-postconstruct-predestroy|Spring PostConstruct and PreDestroy Annotations | Baeldung]]