@PostConstruct注解
最近看面试题,看到有关于@PostConstruct和@PreDestroy两个注解的面试题。它们需要配合spring的@configuration和@bean使用,在@Bean(initMethod = “initMethod”,destroyMethod = “destroyMethod”)中定义,自己创建实例,代码则不会执行。
接下来主要了解它的执行顺序。
新建Son实体类,代码如下:
public class Son {
//构造器
public Son(){
System.out.println("constructMethod....");
}
//普通方法
public void say() {
System.out.println("father......");
}
//初始化方法
public void initMethod() {
System.out.println("initMethod......");
}
//PostConstruct方法
@PostConstruct
public void postConstructMethod() {
System.out.println("postConstructMethod......");
}
//PreDestroy方法
@PreDestroy
public void preDestroyMethod() {
System.out.println("preDestroyMethod......");
}
//销毁方法
public void destroyMethod() {
System.out.println("destroyMethod......");
}
}
@Configuration
public class WebConfig {
@Bean(initMethod = "initMethod",destroyMethod = "destroyMethod")
public Son son(){
return new Son();
}
}
测试运行结果如下:
总结:通过运行测试可以发现,在注入bean的时候一个bean的运行顺序,构造器–>构造器后置方法–>初始化方法–>销毁前置方法–>销毁方法