Spring销毁的几种实现

有这3种方法,但是程序执行完成并没有打印出来。

一定要手动close.手动执行后会调用如下逻辑:
org.springframework.context.support.AbstractApplicationContext#doClose
org.springframework.context.support.AbstractApplicationContext#destroyBeans
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#destroySingletons

我们要注意这个disposableBeans的值从哪里来的?
doCreateBean结束后会注册一个销毁方法。

org.springframework.beans.factory.support.AbstractBeanFactory#registerDisposableBeanIfNecessary

看这个方法:
org.springframework.beans.factory.support.AbstractBeanFactory#requiresDestruction

org.springframework.beans.factory.support.DisposableBeanAdapter#hasDestroyMethod

如果该bean实现了DisposableBean或者实现AutoCloseable接口,如果都没有实现就判断该bean上是否写了销毁方法,如果没有的话使用默认的(inferred)方法,在判断bean是是否有close或者shutdown方法,如果有的话就返回该销毁方法。

或者自己注入一个DestructionAwareBeanPostProcessor,重写该方法,然后返回true即可
org.springframework.beans.factory.support.DisposableBeanAdapter#DisposableBeanAdapter(java.lang.Object, java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.util.List<org.springframework.beans.factory.config.BeanPostProcessor>, java.security.AccessControlContext)
真正的销毁方法处理逻辑:
org.springframework.beans.factory.support.DisposableBeanAdapter#destroy
1.

先执行@PreDestroy方法,也是通过InitDestroyAnnotationBeanPostProcessor该方法反射执行的。
2.执行DisposableBean方法

3.反射执行@Bean里面的方法

问题1:如果@Bean写了销毁的方法,但实际上没有该方法会发生什么?
如果找不到直接报错:

销毁方法可以带参数吗?如果可以的话,可以带多少个参数?以及参数类型

从代码可以看出:可以带参数,但只能带一个参数,而且参数类型只能是boolean,反射的时候默认给true。
注意这里的销毁方法有个适配器模式。DisposableBeanAdapter