Sub topic 16
Lifecycle and SmartLifecycle for start and stop
This chapter assumes you know the callback order from earlier chapters and can run a Spring application. Init and destroy callbacks tie work to a single bean's creation and removal. Some work belongs to the whole application's running period instead, such as starting a message consumer once everything is wired and stopping it before its dependencies close. The Lifecycle and SmartLifecycle interfaces cover that.
Lifecycle versus SmartLifecycle
Lifecycle declares start(), stop() and isRunning(). The container does not call start() on a plain Lifecycle bean when the context refreshes. It calls it only when someone calls start() on the context explicitly.
SmartLifecycle extends Lifecycle and Phased, and adds control over automatic startup:
| Method | Default | Meaning |
|---|---|---|
| `isAutoStartup()` | `true` | Start this bean when the context refreshes |
| `getPhase()` | `Integer.MAX_VALUE` | Ordering of start and stop |
| `stop(Runnable)` | calls `stop()`, then the callback | Lets a bean stop asynchronously |
Phases decide the order
Beans start in ascending phase order, after all singletons have been created. They stop in the reverse order. A bean with a low phase starts early and stops late, so give it to infrastructure that others depend on.
Lifecycle stop() runs before the destruction callbacks (@PreDestroy and DisposableBean), so a stopped bean can still rely on its collaborators being intact.
A worked example
This bean runs a background polling thread. It starts after the context is ready and stops cleanly on close.
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
@Component
class Poller implements SmartLifecycle {
private final AtomicBoolean running = new AtomicBoolean(false);
private Thread worker;
@Override
public void start() {
running.set(true);
worker = new Thread(() -> {
while (running.get()) {
System.out.println("polling");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}, "poller");
worker.start();
}
@Override
public void stop() {
running.set(false);
worker.interrupt();
try {
worker.join(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("poller stopped");
}
@Override
public boolean isRunning() {
return running.get();
}
@Override
public int getPhase() {
return 100;
}
}
public class LifecycleDemo {
public static void main(String[] args) throws Exception {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(Poller.class)) {
Thread.sleep(1000);
}
}
}The program prints polling several times, then poller stopped when the try block closes the context.
Common errors
- Starting work in
@PostConstruct. The context is not fully refreshed at that point, and other beans may not be ready. UseSmartLifecyclefor consumers, schedulers and listeners. - Forgetting
isRunning()state. The container uses it to decide whether to callstop(). If it returnsfalse,stop()is skipped. - Blocking in
stop(). The container waits for each shutdown phase, 30 seconds by default. In Spring Boot you change this withspring.lifecycle.timeout-per-shutdown-phase. For slow shutdowns, overridestop(Runnable callback)and call the callback when finished. - Relying on a plain
Lifecyclebean to auto-start. It will not, unless you callctx.start().
Exercise
Bean A has phase 0 and bean B has phase 200. Both implement SmartLifecycle with default auto-startup. In what order do they start and stop, and when does B's @PreDestroy run relative to B's stop()?
Show answer
A starts first, then B. On shutdown B stops first, then A. B's @PreDestroy runs after B's stop(), because lifecycle stop runs before bean destruction.