Spring自问自答系列四——SmartInitializingSingleton?
今天复习一下Spring IOC源码发现org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons()
方法里除了getBean()
方法执行逻辑外,还有以下代码块:
for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName);
// 如果bean实现了SmartInitializingSingleton
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
// 执行afterSingletonsInstantiated()方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
smartSingleton.afterSingletonsInstantiated();
return null;
}
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
从代码中我们可以推断出,如果bean实现了SmartInitializingSingleton接口,则会在所有bean都初始化成功后执行afterSingletonsInstantiated()方法。
以上是 Spring自问自答系列四——SmartInitializingSingleton? 的全部内容, 来源链接: utcz.com/z/511460.html