How does Lifecycle interface work in Spring? What are “top-level singleton beans”?

前端 未结 5 1599
無奈伤痛
無奈伤痛 2021-02-07 05:13

It is said in Spring javadoc, that \"Note that the Lifecycle interface is only supported on top-level singleton beans.\" Here URL

My LifecycleBeanTest.xml d

5条回答
  •  伪装坚强ぢ
    2021-02-07 05:46

    I never used Lifecycle interface and I am not sure how it is suppose to work. But it looks like simply calling start() on context calls these callbacks:

    AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("...");
    ctx.start();
    

    However typically I use @PostConstruct/@PreDestroy annotations or implement InitializingBean or DisposableBean:

    public class LifecycleBean implements InitializingBean, DisposableBean {
    
        @Override
        public void afterPropertiesSet() {
            //...
        }
    
        @Override
        public void destroy() {
            //...
        }
    
    }
    

    Notice I don't call close() on application context. Since you are creating non-daemon thread in LifecycleBean the JVM remains running even when main exits.

    When you stop that thread JVM exists but does not close application context properly. Basically last non-daemon thread stops, causing the whole JVM to terminate. Here is a bit hacky workaround - when your background non-daemon thread is about to finish, close the application context explicitly:

    public class LifecycleBean implements ApplicationContextAware /* ... */ {
    
        private AbstractApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) {
            this.applicationContext = (AbstractApplicationContext)applicationContext;
        }
    
        public void run() {
            for(int i=0; i<10 && !isInterrupted(); ++i) {
                log.info("Hearbeat {}", i);
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                }
            }
            applicationContext.close();
        }
    
    }
    

提交回复
热议问题