This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Framework 6.0.26! |
Using @PostConstruct
and @PreDestroy
The CommonAnnotationBeanPostProcessor
not only recognizes the @Resource
annotation
but also the JSR-250 lifecycle annotations: jakarta.annotation.PostConstruct
and
jakarta.annotation.PreDestroy
. Introduced in Spring 2.5, the support for these
annotations offers an alternative to the lifecycle callback mechanism described in
initialization callbacks and
destruction callbacks. Provided that the
CommonAnnotationBeanPostProcessor
is registered within the Spring ApplicationContext
,
a method carrying one of these annotations is invoked at the same point in the lifecycle
as the corresponding Spring lifecycle interface method or explicitly declared callback
method. In the following example, the cache is pre-populated upon initialization and
cleared upon destruction:
-
Java
-
Kotlin
public class CachingMovieLister {
@PostConstruct
public void populateMovieCache() {
// populates the movie cache upon initialization...
}
@PreDestroy
public void clearMovieCache() {
// clears the movie cache upon destruction...
}
}
class CachingMovieLister {
@PostConstruct
fun populateMovieCache() {
// populates the movie cache upon initialization...
}
@PreDestroy
fun clearMovieCache() {
// clears the movie cache upon destruction...
}
}
For details about the effects of combining various lifecycle mechanisms, see Combining Lifecycle Mechanisms.
Like |