/** * Return the (raw) singleton object registered under the given name. * <p>Checks already instantiated singletons and also allows for an early * reference to a currently created singleton (resolving a circular reference). * @param beanName the name of the bean to look for * @param allowEarlyReference whether early references should be created or not * @return the registered singleton object, or {@code null} if none found */ @Nullable protected Object getSingleton(String beanName, boolean allowEarlyReference){ // 从缓存(ConcurrentHashMap)中获取bean实例 Object singletonObject = this.singletonObjects.get(beanName); // 如果bean实例为null,且正在创建中 if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { // double-check:1 synchronized (this.singletonObjects) { // 从缓存(ConcurrentHashMap)中获取early bean实例 singletonObject = this.earlySingletonObjects.get(beanName); // 如果bean实例为null,且允许创建early reference if (singletonObject == null && allowEarlyReference) { // double-check:2 // 这里并非bean实例,而是创建bean实例的工厂对象 ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { // 返回真正的bean singletonObject = singletonFactory.getObject(); this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } return singletonObject; }