Using @PostConstruct
and @PreDestroy
"@35" 不仅识别 "@36" 注解,还识别 JSR-250 生命周期注解:"@37" 和 "@38"。在 Spring 2.5 中引入的对这些注解的支持为 "@41" 和 "@42" 中描述的生命周期回调机制提供了一种替代方案。只要 "@39" 在 Spring "@40" 中注册,那么在生命周期中的同一时间点调用携带这些注解之一的方法,此时也会调用相应的 Spring 生命周期接口方法或显式声明的回调方法。在以下示例中,高速缓存会在初始化时预先填充,并在销毁时清除:
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...
}
}
有关组合各种生命周期机制的影响的详细信息,请参阅 "@@43"。
For details about the effects of combining various lifecycle mechanisms, see Combining Lifecycle Mechanisms.
与 Like |