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
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();
}
}