对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
用@PostConstruct
和@PreDestroy
这CommonAnnotationBeanPostProcessor
不仅识别@Resource
注解
还有 JSR-250 生命周期注释:jakarta.annotation.PostConstruct
和jakarta.annotation.PreDestroy
.在 Spring 2.5 中引入,对这些
annotations 提供了初始化回调和销毁回调中描述的生命周期回调机制的替代方案。前提是CommonAnnotationBeanPostProcessor
在 Spring 中注册ApplicationContext
,
带有这些 Comments 之一的方法在生命周期的同一点被调用
作为相应的 Spring 生命周期接口方法或显式声明的回调
方法。在以下示例中,缓存在初始化时预先填充,并且
销毁时清除:
-
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...
}
}
有关组合各种生命周期机制的效果的详细信息,请参阅组合生命周期机制。
喜欢 |