Spring @PostConstruct和@PreDestroy注释
时间:2020-01-09 10:44:35 来源:igfitidea点击:
在这篇文章中,我们将看到在Spring bean生命周期中在何处以及如何使用@PostConstruct和@PreDestroy注释。
Spring @PostConstruct注释
PostConstruct注释用于需要依赖注入完成以执行任何初始化之后要执行的方法上。
任何用@PostConstruct注释的方法都被视为初始化回调,该回调与容器对bean生命周期的管理挂钩。一旦容器实例化了bean,就调用该方法以执行任何bean初始化。
Spring @PreDestroy注释
PreDestroy注释用于在容器删除bean实例的过程中调用的方法。
任何用@PreDestroy注释的方法都被视为销毁回调,当包含它的容器被销毁时,该方法可使bean获得回调。这样就有机会在销毁bean之前执行一些清理。
Spring @PostConstruct和@PreDestroy注释示例
请注意,使用@PostConstruct和@PreDestroy注释需要javax注释API。我们需要为此从Java 9开始添加依赖项。
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
这是一个带有方法的类,该方法使用@PostConstruct和@PreDestroy注释进行注释。
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
public void myMethod() {
System.out.println("In MyMethod of MyBean class");
}
@PostConstruct
public void initMethod() {
System.out.println("calling init method for post construct");
}
@PreDestroy
public void destroyMethod() {
System.out.println("calling destroy method for pre destroy");
}
}
AppConfig类
@Configuration
@ComponentScan("com.theitroad.springexample")
public class AppConfig {
}
请更改基本软件包以根据软件包结构进行扫描。
使用main方法的类来运行示例。
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.close();
}
}
如我们所见,此类仅使用AppConfig作为配置来创建上下文,然后关闭上下文并没有做太多事情。
创建上下文时,将实例化所有bean,因此应在此处调用@PostConstruct注释的方法。当上下文关闭时,应调用以@PreDestroy注释的方法。
输出:
19:20:08.649 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myBean' call init method for post construct call destroy method for pre destroy

