目的
spring提供了三种初始化方法:
1、@PostConstruct、@PreDestory
2、实现 InitializingBean DisposableBean 接口,并实现对应的afterPropertiesSet()和destroy()方法
3、设置init-method和destory-method
本文主要解析三个初始化和销毁方法的源码
只是有一个点需要注意:@PostConstruct、@PreDestory这两个注解是通过后置处理器完成处理的 --> org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization
其他两种方式,不是通过后置处理器完成的
源码
1、三种初始化方法的优先级从高到低;在spring官方文档也有明确指出
Multiple lifecycle mechanisms configured for the same bean, with
different initialization methods, are called as follows:
Methods annotated with @PostConstruct
afterPropertiesSet() as defined by the InitializingBean callback interface
A custom configured init() method
Destroy methods are called in the same order:
Methods annotated with @PreDestroy
destroy() as defined by the DisposableBean callback interface
A custom configured destroy() method
优先级之所以是这样,和源码中对三种配置方式处理的优先级有关系
测试代码
public class UserService04 implements InitializingBean,DisposableBean {
public UserService04() {
}
@Override
public void destroy() throws Exception {
System.out.println("实现接口DisposableBean销毁");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("实现接口InitializingBean初始化");
}
public void init(){
System.out.println("initMethod");
}
public void destroyConfig(){
System.out.println("destroyMethod");
}
@PostConstruct
public void testPost(){
System.out.println("注解PostConstruct init");
}
@PreDestroy
public void testDestroy(){
System.out.println("注解PreDestroy 销毁");