使用 @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...
}
}
有關組合各種生命週期機制效果的詳細資訊,請參閱組合生命週期機制。
與 |