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