스프링 빈 라이프사이클

6899 단어 java


라이프사이클 코드 예제




@Component
public class LifeCycleDemoBean implements InitializingBean, DisposableBean, BeanNameAware,
        BeanFactoryAware, ApplicationContextAware {


    public LifeCycleDemoBean() {
        System.out.println("## 1. I'm in the LifeCycleBean Constructor");
    }

    /**
     * {@link BeanNameAware}
     */
    @Override
    public void setBeanName(String name) {
        System.out.println("## 2. My Bean Name is: " + name);
    }

    /**
     * {@link BeanFactoryAware}
     */
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("## 3. Bean Factory has been set");
    }

    /**
     * {@link ApplicationContextAware}
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("## 4. Application context has been set");
    }

    /**
     * {@link LifeCycleDemoBeanPostProcessor}
     */
    public void beforeInit(){
        System.out.println("## 5. Before Init - Called by BeanPostProcessor: LifeCycleDemoBeanPostProcessor");
    }

    @PostConstruct
    public void postConstruct(){
        System.out.println("## 6. The Post Construct annotated method has been called");
    }

    /**
     * {@link InitializingBean}
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("## 7. The LifeCycleBean has its properties set!");
    }

    /**
     * {@link LifeCycleDemoBeanPostProcessor}
     */
    public void afterInit(){
        System.out.println("## 8. After init called by Bean Post Processor");
    }

    @PreDestroy
    public void preDestroy() {
        System.out.println("## 9. The PreDestroy annotated method has been called");
    }

    /**
     * {@link DisposableBean}
     */
    @Override
    public void destroy() throws Exception {
        System.out.println("## 10. The Lifecycle bean has been terminated");
    }
}


위의 코드를 실행하면 인쇄된 메시지가 숫자 표시 순서대로 콘솔에 표시되며 이는 수명 주기 이미지가 표시하는 것과 정확히 동일합니다.

자세한 내용은 spring-bean-lifecycle을 확인하세요.

좋은 웹페이지 즐겨찾기