sharedInstance = getSingleton(beanName, () -> {try {return createBean(beanName, mbd, args);}:单例初始化,这个方法比较简单,主要关注下和循坏依赖相关的逻辑
/* org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java:201 */
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//循环依赖相关:初始化前先singletonsCurrentlyInCreation.add(beanName)
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//lamda表达式:其实是调用createBean(beanName, mbd, args):Bean初始化
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//循环依赖相关:初始化后singletonsCurrentlyInCreation.remove(beanName)
afterSingletonCreation(beanName);
}
if (newSingleton) {
//初始化完后
//this.singletonObjects.put(beanName, singletonObject);放入到单例容器中
//this.singletonFactories.remove(beanName);清空循环依赖相关的两个打标
//this.earlySingletonObjects.remove(beanName);
//this.registeredSingletons.add(beanName);放入单例beanName容器中
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
createBean(beanName, mbd, args):初始化实例,这个表方法注意一下,初始化实例前,留机会给BeanPostProcessor初始化代理类直接返回代理类初始化实例










