使用 @PostConstruct@PreDestroy

CommonAnnotationBeanPostProcessor 不僅識別 @Resource 註解,還識別 JSR-250 生命週期註解:jakarta.annotation.PostConstructjakarta.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...
	}
}

有關組合各種生命週期機制效果的詳細資訊,請參閱組合生命週期機制

@Resource 類似,@PostConstruct@PreDestroy 註解型別是 JDK 6 到 8 標準 Java 庫的一部分。然而,整個 javax.annotation 包在 JDK 9 中與核心 Java 模組分離,並在 JDK 11 中最終移除。從 Jakarta EE 9 開始,該包現在位於 jakarta.annotation 中。如果需要,現在需要透過 Maven Central 獲取 jakarta.annotation-api artifact,只需將其像任何其他庫一樣新增到應用程式的類路徑中即可。