创建一个Bean
@Component
public class LifeCycleBean {
//执行顺序:构造方法--》autowire--》PostConstruct初始化方法--》容器关闭时,单例对象执行销毁方法
static final Logger logger=LoggerFactory.getLogger(LifeCycleBean.class);
public LifeCycleBean() {
System.out.println("构造");
}
@Autowired
public void autowire(@Value("${JAVA_HOME}")String home){
System.out.println("依赖注入:"+home);
}
@PostConstruct
public void init(){
System.out.println("初始化");
}
@PreDestroy
public void destory(){
System.out.println("销毁");
}
}
启动容器
ConfigurableApplicationContext context = SpringApplication.run(SpringlearningApplication.class, args);
context.close();
打印结果
容器关闭后:
销毁
执行顺序:
构造方法-->autowire-->PostConstruct初始化方法-->容器关闭时,单例对象执行销毁方法
自定义Bean后处理器
实现InstantiationAwareBeanPostProcessor和DestructionAwareBeanPostProcessor两个接口
@Component
public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor {
@Override//销毁之前执行
public void postProcessBeforeDestruction(Object o, String s) throws BeansException {
if(s.equals("lifeCycleBean")){
System.out.println("------销毁之前执行-------");
}
}
@Override//实例化之前执行,返回的对象会替换原本的bean
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean")) System.out.println("------实例化之前------");
return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
}
@Override//实例化之后执行,返回的对象会替换原本的bean
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean")) System.out.println("------实例化之后------");
return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
}
@Override//依赖注入阶段执行@Autowired @Value @Resource
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean")) System.out.println("------依赖注入------");
return InstantiationAwareBeanPostProcessor.super.postProcessProperties(pvs, bean, beanName);
}
@Override//初始化之前执行,返回的对象会替换原本的bean,如@PostConstruct @ConfigurationProperties
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean"))System.out.println("------初始化之前------");
return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
@Override//初始话之后执行,如代理增强
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean"))System.out.println("------初始化之后------");
return InstantiationAwareBeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
执行结果: