Mastering Spring Boot Lifecycle: Practical SmartLifecycle Examples
Explore the Spring Boot 3 lifecycle mechanisms, including the core Lifecycle and SmartLifecycle interfaces, with detailed code samples that demonstrate bean start/stop control, phase ordering, shutdown timeouts, and scheduled task management, enabling developers to fine‑tune application behavior during startup and shutdown.
Introduction
Spring provides the Lifecycle interface, which defines three essential methods for bean lifecycle control:
public interface Lifecycle {
/** Start this component. */
void start();
/** Stop this component. */
void stop();
/** Check if the component is running. */
boolean isRunning();
}Any Spring‑managed bean can implement Lifecycle. When the ApplicationContext receives start or stop signals, it delegates to a LifecycleProcessor that invokes the appropriate methods.
public interface LifecycleProcessor extends Lifecycle {
// Called on context refresh (e.g., auto‑start components)
void onRefresh();
// Called on context close (e.g., auto‑stop components)
void onClose();
}For finer‑grained control, consider implementing the extended SmartLifecycle interface.
Practical Examples
2.1 Basic Usage
A simple bean implementing SmartLifecycle:
public class PackServer implements SmartLifecycle {
boolean isRunning = false;
@Override
public void start() {
isRunning = true;
System.out.println("PackServer start...");
}
@Override
public void stop() {
System.out.println("PackServer stop...");
isRunning = false;
}
@Override
public boolean isRunning() {
return isRunning;
}
}Testing the bean:
ApplicationContext context = ...;
context.refresh(); // starts the bean
context.close(); // stops the beanOutput:
PackServer start...
PackServer stop...2.2 Controlling Startup Order
Implement getPhase() to influence start/stop order. Beans with a lower phase value start earlier and stop later.
public class PackServer implements SmartLifecycle {
@Override public int getPhase() { return 4; }
}
public class CustomServer implements SmartLifecycle {
@Override public int getPhase() { return 2; }
}Resulting execution order:
CustomServer start...
PackServer start...
PackServer stop...
CustomServer stop...2.3 Configuring Shutdown Timeout
Customize the timeout for each shutdown phase by providing a DefaultLifecycleProcessor bean:
@Bean
public DefaultLifecycleProcessor lifecycleProcessor() {
DefaultLifecycleProcessor p = new DefaultLifecycleProcessor();
p.setTimeoutPerShutdownPhase(2000); // 2 seconds
return p;
}When a bean’s stop(Runnable) takes longer than the configured timeout, Spring logs a timeout warning (illustrated below).
2.4 Managing Scheduled Tasks with SmartLifecycle
Implement a background task that starts with the application and stops gracefully:
@Component
public class DataSyncTask implements SmartLifecycle {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private volatile boolean running = false;
@Override public void start() {
Runnable task = () -> System.out.println("Sync data task...");
scheduler.scheduleAtFixedRate(task, 0, 30, TimeUnit.SECONDS);
running = true;
}
@Override public void stop() {
scheduler.shutdownNow();
running = false;
}
@Override public boolean isRunning() { return running; }
@Override public int getPhase() { return -1; } // start as early as possible
}This bean automatically begins data synchronization when the Spring context starts and stops the scheduler on shutdown.
These examples demonstrate how to leverage Lifecycle and SmartLifecycle to gain precise control over bean lifecycles, startup ordering, shutdown timeouts, and background task management in Spring Boot applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
