java / expert
Snippet
Orchestrating Component Lifecycle with SmartLifecycle
The SmartLifecycle interface allows components to participate in the ApplicationContext lifecycle. It provides fine-grained control over the order in which beans start and stop using the 'getPhase' method, which is crucial for components that depend on other services being fully initialized (like message listeners).
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Componentpublic class GracefulService implements SmartLifecycle {private boolean isRunning = false;@Overridepublic void start() {// Initialize heavy resources or connect to message brokersthis.isRunning = true;}@Overridepublic void stop() {// Custom shutdown logic, e.g., draining queuesthis.isRunning = false;}@Overridepublic boolean isRunning() {return this.isRunning;}@Overridepublic int getPhase() {return Integer.MAX_VALUE; // Defines the startup/shutdown order}}
spring
Breakdown
1
public class GracefulService implements SmartLifecycle
Implements the extended lifecycle interface for better control over bean transitions.
2
public int getPhase()
Returns an integer determining the priority; lower values start first and stop last.