Spring容器在创建时注册了销毁逻辑(单例Bean)
//注册源码
//org.springframework.beans.factory.support.AbstractBeanFactory#registerDisposableBeanIfNecessary
//实现注册:注解,实现接口,通过bdf指定销毁方法
@jakarta.annotation.PreDestroy
@Component
public class UserService implements DisposableBean {}
//初始化和销毁的方法都在这里存储
org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#buildLifecycleMetadata
//把实现的注册包装成 DisposableBeanAdapter,存入map
org.springframework.beans.factory.support.DisposableBeanAdapter
Spring容器关闭的时候触发
//进程正常结束的时候
context.registerShutdownHook();
context.close();
Spring容器关闭过程
publishEvent
lifecycleProcessor.onClose()
//只销毁单例bean
destroyBeans
applicationListeners.clear()
适配器模式的使用场景
在销毁时,Spring会找出实现了DisposableBean接口的Bean。
但是我们在定义一个Bean时,如果这个Bean实现了DisposableBean接口,或者实现了 AutoCloseable接口,或者在BeanDefinition中指定了destroyMethodName,那么这个Bean都属 于“DisposableBean”,这些Bean在容器关闭时都要调用相应的销毁方法。
所以,这里就需要进行适配,将实现了DisposableBean接口、或者AutoCloseable接口等适配成实 现了DisposableBean接口,所以就用到了DisposableBeanAdapter。 会把实现了AutoCloseable接口的类封装成DisposableBeanAdapter,而DisposableBeanAdapter 实现了DisposableBean接口。
Spring中依赖注入的方式
set方法注入
构造方法注入
@Autowired注解
- 属性上:先根据属性类型去找Bean,如果找到多个再根据属性名确定一个
- 构造方法上:先根据方法参数类型去找Bean,如果找到多个再根据参数名确定一个
- set方法上:先根据方法参数类型去找Bean,如果找到多个再根据参数名确定一个