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