https://blog.csdn.net/weixin_43735348/article/details/128824737
https://www.cnblogs.com/shigongp/p/16751189.html
### ----------------------------------------@PostConstruct和@PreDestroy
@PostConstruct 注解加在一个 bean 的方法上,当此 bean 被 spring-ioc 初始化时,自动调用此方法。注意,此类的实例需要作为 bean 交由 spring-ioc 管理时,注解才能生效。
public Object Students {
@PostConstruct 所在的类上不用加其他注解,就会把类变为bean
public void init() {
// doSomething
}
@PreDestroy 触发点:调用ApplicationContext.close()
public void destroy() {
System.out.println("PreDestroy");
}
}
实现原理是借助了 BeanPostProcessor 的机制,具体地说,是 InitDestroyAnnotationBeanPostProcessor。
-> SpringApplication.run()
-> ...
-> AbstractApplicationContext.finishBeanFactoryInitialization()
-> AbstractBeanFactory.getBean() name=students
...
-> AbstractAutowireCapableBeanFactory.populateBean()
-> AbstractAutowireCapableBeanFactory.initializeBean()
applyBeanPostProcessorsBeforeInitialization() 执行前置处理
-> AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization()
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) { 遍历BeanPostProcessor
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
-> InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization()
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
metadata.invokeInitMethods(bean, beanName); 此方法执行后,执行到@PostConstruct,
完成自定义逻辑
}
catch (InvocationTargetException ex) {
throw new BeanCreationException( );
}
catch (Throwable ex) {
throw new BeanCreationException( );
}
return bean;
}
@PreDestroy触发起点
-> SpringApplication.run()
contxt.close()
-> AbstractApplicationContext.close()
-> DisposableBeanAdapter.destroy()
for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
processor.postProcessBeforeDestruction(this.bean, this.beanName);
}
-> InitDestroyAnnotationBeanPostProcessor.postProcessBeforeDestruction()
metadata.invokeDestroyMethods(bean, beanName) 此方法执行后,执行到@PreDestroy,
完成自定义逻辑