0 day streak
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
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
@Component
public class GracefulService implements SmartLifecycle {
private boolean isRunning = false;
@Override
public void start() {
// Initialize heavy resources or connect to message brokers
this.isRunning = true;
}
@Override
public void stop() {
// Custom shutdown logic, e.g., draining queues
this.isRunning = false;
}
@Override
public boolean isRunning() {
return this.isRunning;
}
@Override
public 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.