Using @PostConstruct and @PreDestroy

"@35" 不仅识别 "@36" 注解,还识别 JSR-250 生命周期注解:"@37" 和 "@38"。在 Spring 2.5 中引入的对这些注解的支持为 "@41" 和 "@42" 中描述的生命周期回调机制提供了一种替代方案。只要 "@39" 在 Spring "@40" 中注册,那么在生命周期中的同一时间点调用携带这些注解之一的方法,此时也会调用相应的 Spring 生命周期接口方法或显式声明的回调方法。在以下示例中,高速缓存会在初始化时预先填充,并在销毁时清除:

The CommonAnnotationBeanPostProcessor not only recognizes the @Resource annotation but also the JSR-250 lifecycle annotations: jakarta.annotation.PostConstruct and jakarta.annotation.PreDestroy. Introduced in Spring 2.5, the support for these annotations offers an alternative to the lifecycle callback mechanism described in initialization callbacks and destruction callbacks. Provided that the CommonAnnotationBeanPostProcessor is registered within the Spring ApplicationContext, a method carrying one of these annotations is invoked at the same point in the lifecycle as the corresponding Spring lifecycle interface method or explicitly declared callback method. In the following example, the cache is pre-populated upon initialization and cleared upon destruction:

  • 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...
	}
}

有关组合各种生命周期机制的影响的详细信息,请参阅 "@@43"。

For details about the effects of combining various lifecycle mechanisms, see Combining Lifecycle Mechanisms.

@Resource 一样,@PostConstruct@PreDestroy 注解类型是从 JDK 6 到 JDK 8 的 Java 标准库的一部分。但是,整个 javax.annotation 包已从 JDK 9 中的核心 Java 模块中分离出来,并最终在 JDK 11 中删除。从 Jakarta EE 9 开始,该包现在位于 jakarta.annotation 中。如果需要,现在需要通过 Maven Central 获取 jakarta.annotation-api 工件,只需将其添加到应用程序的类路径中,就像任何其他库一样。

Like @Resource, the @PostConstruct and @PreDestroy annotation types were a part of the standard Java libraries from JDK 6 to 8. However, the entire javax.annotation package got separated from the core Java modules in JDK 9 and eventually removed in JDK 11. As of Jakarta EE 9, the package lives in jakarta.annotation now. If needed, the jakarta.annotation-api artifact needs to be obtained via Maven Central now, simply to be added to the application’s classpath like any other library.