初始化方法:
1、实现InitializingBean,重写afterPropertiesSet方法
2、直接使用initBean方法,需要指定init-method
3、使用@PostConstruct注解
private String name;
/**
* 构造方法
* @param name
*/
public InitSortTest(String name) {
this.name = name;
System.out.println("InitSortTest name = [" + name + "]");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean afterPropertiesSet 执行");
}
public void initBean(){
System.out.println("initBean 执行");
}
@PostConstruct
public void postConstruct() {
System.out.println("@PostConstruct 执行");
}
销毁方法:
1、实现 DisposableBean,重写destroy方法;
2、直接使用destroy方法,需要指定destroy-method
3、使用@PreDestroy注解
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean destroy 执行");
}
public void destroyBean() {
System.out.println("destroyBean 执行");
}
@PreDestroy
public void preDestroy() {
System.out.println("@PreDestroy 执行");
}
创建配置类
@Configuration
public class InitConfig {
@Bean(initMethod = "initBean",destroyMethod = "destroyBean")
public InitSortTest initSortTest() {
return new InitSortTest("测试");
}
}
启动服务
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(DemoApplication.class, args);
InitSortTest initSortTest = configurableApplicationContext.getBean(InitSortTest.class);
configurableApplicationContext.close();
}
}
运行结果如下图:
我们可以得出
初始化顺序:构造方法 → @PostConstruct → afterPropertiesSet → initBean。
销毁顺序 :@PreDestroy → DisposableBean destroy → destroyBean
通过源码我们也可以看得出具体的顺序
首先通过debug我们发现@PostConstruct 是在 BeanPostProcessor的前置处理中执行的,所有优先级很高。
然后afterPropertiesSet 与initbean的执行顺序源码中也有描述
所有顺序也是很明显的。
此处注意,afterPropertiesSet的调用,是直接强制类型转换的调用,initbean是采用的反射机制。