使用 @PostConstruct
和 @PreDestroy
CommonAnnotationBeanPostProcessor
不仅识别 @Resource
注解,还识别 JSR-250 生命周期注解:jakarta.annotation.PostConstruct
和 jakarta.annotation.PreDestroy
。这些注解的支持在 Spring 2.5 中引入,为 初始化回调 和 销毁回调 中描述的生命周期回调机制提供了一种替代方案。只要 CommonAnnotationBeanPostProcessor
在 Spring 的 ApplicationContext
中注册,带有这些注解之一的方法将在与相应的 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...
}
}
有关组合各种生命周期机制效果的详细信息,请参阅组合生命周期机制。
与 |