I'm trying to understand the Lifecycle
interface logic.
The documentation for Lifecycle
says:
Containers will propagate start/stop signals to all components that apply within each container, e.g. for a stop/restart scenario at runtime.
But it seems that cantainer doesn't call this methods (start/stop) at all.
For example the result for next code snippet is only single output ">> call: is running: false"
@Configuration
public class TestApp implements Lifecycle {
boolean runStatus = false;
@Override
public void start() {
System.err.println(">> call: start (Lifecycle)");
runStatus = true;
}
@Override
public void stop() {
System.err.println(">> call: stop (Lifecycle)");
runStatus = false;
}
@Override
public boolean isRunning() {
System.err.println(">> call: is running: " + runStatus);
return runStatus;
}
public static void main(String[] args) {
AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(TestApp.class);
ctx.stop();
}
}
P.S. I heard about SmartLifecycle
and it works fine. But I'm interesting in how can we correctly use the start/stop methods from Lifecycle
.
You should manually start()
and stop()
the context.
@Configuration
public class TestApp implements Lifecycle {
boolean runStatus = false;
public TestApp (){}
@Bean
public TestApp testApp(){
return new TestApp();
}
@Override
public void start() {
System.err.println(">> call: start (Lifecycle)");
runStatus = true;
}
@Override
public void stop() {
System.err.println(">> call: stop (Lifecycle)");
runStatus = false;
}
@Override
public boolean isRunning() {
System.err.println(">> call: is running: " + runStatus);
return runStatus;
}
public static void main(String[] args) {
AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(TestApp.class);
ctx.start();
TestApp ta = ctx.getBean(TestApp.class);
ctx.stop();
}
}