; synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// 省略无关代码
beforeSingletonCreation(beanName); // 步骤A
boolean newSingleton = false;
// 省略无关代码
try {
singletonObject = singletonFactory.getObject();// 步骤B
newSingleton = true;
}
// 省略无关代码
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);// 步骤C
}
if (newSingleton) {
addSingleton(beanName, singletonObject);// 步骤D
}
}
return singletonObject;
}
}
获取单例对象的主要逻辑就是此方法实现的,主要分为上面四个步骤,继续挨个看:
步骤A:
1 protected void beforeSingletonCreation(String beanName) {
2 // 判断,并首次将beanName即teacher放入singletonsCurrentlyInCreation中
3 if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
4 throw new BeanCurrentlyInCreationException(beanName);
5 }
6 }
步骤C:
1 protected void afterSingletonCreation(String beanName) {
2 // 得到单例对象后,再讲beanName从singletonsCurrentlyInCreation中移除
3 if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
4 throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
5 }
6 }
步骤D:
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);//添加单例对象到map中
this.singletonFactories.remove(beanName);//从早期暴露的工厂中移除,此map在解决循环依赖中发挥了关键的作用
this.earlySingletonObjects.remove(beanName);//从早期暴露的对象map中移除
this.regi