0
# Lifecycle Management
1
2
Bean lifecycle management providing comprehensive control over component initialization, destruction, startup/shutdown phases, and lifecycle callbacks. This includes Lifecycle interfaces, initialization/destruction hooks, and phased startup for complex application orchestration.
3
4
## Capabilities
5
6
### Lifecycle Interfaces
7
8
```java { .api }
9
/**
10
* A common interface defining methods for start/stop lifecycle control.
11
*/
12
public interface Lifecycle {
13
/**
14
* Start this component.
15
*/
16
void start();
17
18
/**
19
* Stop this component, typically in a synchronous fashion.
20
*/
21
void stop();
22
23
/**
24
* Check whether this component is currently running.
25
* @return whether the component is currently running
26
*/
27
boolean isRunning();
28
}
29
30
/**
31
* An extension of the Lifecycle interface for those objects that require to be started upon ApplicationContext refresh and/or shutdown in a particular order.
32
*/
33
public interface SmartLifecycle extends Lifecycle, Phased {
34
/** The default phase for SmartLifecycle */
35
int DEFAULT_PHASE = Integer.MAX_VALUE;
36
37
/**
38
* Returns true if this Lifecycle component should get started automatically by the container at the time that the containing ApplicationContext gets refreshed.
39
* @return whether to start automatically
40
*/
41
default boolean isAutoStartup() {
42
return true;
43
}
44
45
/**
46
* Indicates that a Lifecycle component must stop if it is currently running.
47
* @param callback a callback which the implementation must invoke once the shutdown process is complete
48
*/
49
default void stop(Runnable callback) {
50
stop();
51
callback.run();
52
}
53
54
/**
55
* Return the phase value of this object.
56
* @return the phase value
57
*/
58
default int getPhase() {
59
return DEFAULT_PHASE;
60
}
61
}
62
63
/**
64
* Interface for objects that may participate in a phased process such as lifecycle management.
65
*/
66
public interface Phased {
67
/**
68
* Return the phase value of this object.
69
* @return the phase value
70
*/
71
int getPhase();
72
}
73
74
/**
75
* Strategy interface for processing Lifecycle beans within the ApplicationContext.
76
*/
77
public interface LifecycleProcessor extends Lifecycle {
78
/**
79
* Notification of context refresh, e.g. for auto-starting components.
80
*/
81
void onRefresh();
82
83
/**
84
* Notification of context close, e.g. for auto-stopping components.
85
*/
86
void onClose();
87
}
88
```
89
90
### Initialization and Destruction Callbacks
91
92
```java { .api }
93
/**
94
* Interface to be implemented by beans that need to react once all their properties have been set by a BeanFactory.
95
*/
96
public interface InitializingBean {
97
/**
98
* Invoked by the containing BeanFactory after it has set all bean properties and satisfied BeanFactoryAware, ApplicationContextAware etc.
99
* @throws Exception in the event of misconfiguration or if initialization fails for any other reason
100
*/
101
void afterPropertiesSet() throws Exception;
102
}
103
104
/**
105
* Interface to be implemented by beans that want to release resources on destruction.
106
*/
107
public interface DisposableBean {
108
/**
109
* Invoked by the containing BeanFactory on destruction of a bean.
110
* @throws Exception in case of shutdown errors
111
*/
112
void destroy() throws Exception;
113
}
114
115
/**
116
* Subinterface of BeanPostProcessor that adds a before-destruction callback.
117
*/
118
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
119
/**
120
* Apply this BeanPostProcessor to the given bean instance before its destruction.
121
* @param bean the bean instance to process
122
* @param beanName the name of the bean
123
* @throws BeansException in case of errors
124
*/
125
void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;
126
127
/**
128
* Determine whether the given bean instance requires destruction by this post-processor.
129
* @param bean the bean instance to check
130
* @return true if postProcessBeforeDestruction should be called for this bean instance
131
*/
132
default boolean requiresDestruction(Object bean) {
133
return true;
134
}
135
}
136
```
137
138
### Lifecycle Annotations
139
140
```java { .api }
141
/**
142
* Annotation that marks a method as the target for a bean lifecycle callback.
143
*/
144
@Target({ElementType.METHOD})
145
@Retention(RetentionPolicy.RUNTIME)
146
public @interface PostConstruct {
147
}
148
149
/**
150
* Annotation that marks a method as the target for a bean destruction callback.
151
*/
152
@Target({ElementType.METHOD})
153
@Retention(RetentionPolicy.RUNTIME)
154
public @interface PreDestroy {
155
}
156
```
157
158
### Usage Examples
159
160
**Lifecycle Implementation:**
161
162
```java
163
@Component
164
public class DatabaseConnectionManager implements SmartLifecycle {
165
private boolean running = false;
166
private DataSource dataSource;
167
168
@Override
169
public void start() {
170
if (!running) {
171
// Initialize database connections
172
initializeConnections();
173
running = true;
174
System.out.println("Database connection manager started");
175
}
176
}
177
178
@Override
179
public void stop() {
180
if (running) {
181
// Close database connections
182
closeConnections();
183
running = false;
184
System.out.println("Database connection manager stopped");
185
}
186
}
187
188
@Override
189
public boolean isRunning() {
190
return running;
191
}
192
193
@Override
194
public int getPhase() {
195
return 1000; // Start early, stop late
196
}
197
198
@Override
199
public boolean isAutoStartup() {
200
return true;
201
}
202
}
203
204
@Component
205
public class CacheManager implements InitializingBean, DisposableBean {
206
private Cache cache;
207
208
@Override
209
public void afterPropertiesSet() throws Exception {
210
// Initialize cache after all properties are set
211
this.cache = createCache();
212
System.out.println("Cache initialized");
213
}
214
215
@Override
216
public void destroy() throws Exception {
217
// Clean up cache resources
218
if (cache != null) {
219
cache.shutdown();
220
System.out.println("Cache destroyed");
221
}
222
}
223
}
224
225
@Component
226
public class AnnotationBasedLifecycle {
227
228
@PostConstruct
229
public void initialize() {
230
System.out.println("Component initialized with @PostConstruct");
231
// Perform initialization logic
232
}
233
234
@PreDestroy
235
public void cleanup() {
236
System.out.println("Component cleaned up with @PreDestroy");
237
// Perform cleanup logic
238
}
239
}
240
```