Spring版本
5.2.5.RELEASE
源碼解讀
在《Spring源碼解析(八)-創(chuàng)建單例bean》的doCreateBean方法的最后一步,調(diào)用了registerDisposableBeanIfNecessary進(jìn)行了bean的銷毀邏輯的注冊
1 AbstractAutowireCapableBeanFactory#registerDisposableBeanIfNecessary
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
// 獲取訪問控制上下文
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// 單例模式
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
// 為給定bean注冊一個(gè)可以執(zhí)行包括DestructionAwareBeanPostProcessors、DisposableBean接口,自定義銷毀方法的DisposableBean實(shí)現(xiàn)
// 往disposableBeans緩存map寫入beanName和DisposableBeanAdapter的映射關(guān)系
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
// 其他模式
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
// 交由自定義的scope進(jìn)行銷毀邏輯
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}
如果是單例模式,構(gòu)造一個(gè)DisposableBeanAdapter
對象,之后,將<beanName,構(gòu)造出來的DisposableBeanAdapter對象>寫入緩存map
如果是其他模式,則交由scope進(jìn)行銷毀邏輯的處理