/** * 负责单例bean的初始化 * Finish the initialization of this context's bean factory, * initializing all remaining singleton beans. */ protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){ // Initialize conversion service for this context. //最先初始化名字为 conversionService的类,conversionService类 它用来将前端传过来的参数和后端的 controller 方法上的参数进行绑定的时候用 //尤其是用于非基础类型的转换 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( //初始化在getBean()方法中实现 beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); }
// Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. // 先初始化 LoadTimeWeaverAware 类型的 Bean aop相关注:大概有个印象,以后解析aop会和它串起来。 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); }
// Stop using the temporary ClassLoader for type matching. beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes. //freeze的单词意思是冻结,这个时候已经开始预初始化, bean 定义解析、加载、注册先停止 beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons. //开始初始化 beanFactory.preInstantiateSingletons(); }
@Override publicvoidpreInstantiateSingletons() throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); }
// Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. // this.beanDefinitionNames 保存了所有的 beanNames
// Guarantee initialization of beans that the current bean depends on. // 先初始化依赖的所有 Bean,这个很好理解。 // 注意,这里的依赖指的是 depends-on 中定义的依赖 String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { // 检查是不是有循环依赖,这里的循环依赖和我们前面说的循环依赖又不一样 if (isDependent(beanName, dep)) { thrownewBeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } // 注册一下依赖关系 registerDependentBean(dep, beanName); try { // 先初始化被依赖项 getBean(dep); } catch (NoSuchBeanDefinitionException ex) { thrownewBeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } }
// Create bean instance. // 如果是 singleton scope 的,创建 singleton 的实例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { // 执行创建 Bean,详情继续深入 // 第三个参数 args 数组代表创建实例需要的参数,不就是给构造方法用的参数,或者是工厂 Bean 的参数嘛,不过要注意,在我们的初始化阶段,args 是 null。 // 这回我们要到一个新的类了 AbstractAutowireCapableBeanFactory,看类名,AutowireCapable?类名是不是也说明了点问题了。 // 主要是为了以下场景,采用 @Autowired 注解注入属性值: return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } // 如果是 prototype scope 的,创建 prototype 的实例 elseif (mbd.isPrototype()) { // It's a prototype -> create a new instance. ObjectprototypeInstance=null; try { beforePrototypeCreation(beanName); // 执行创建 Bean prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); }
else { StringscopeName= mbd.getScope(); if (!StringUtils.hasLength(scopeName)) { thrownewIllegalStateException("No scope name defined for bean ´" + beanName + "'"); } Scopescope=this.scopes.get(scopeName); if (scope == null) { thrownewIllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { ObjectscopedInstance= scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { thrownewBeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } }
// Check if required type matches the type of the actual bean instance. // 最后,检查一下类型对不对,不对的话就抛异常,对的话就返回了 if (requiredType != null && !requiredType.isInstance(bean)) { try { TconvertedBean= getTypeConverter().convertIfNecessary(bean, requiredType); if (convertedBean == null) { thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } return convertedBean; } catch (TypeMismatchException ex) { if (logger.isTraceEnabled()) { logger.trace("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }
if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } RootBeanDefinitionmbdToUse= mbd;
// Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. // 确保 BeanDefinition 中的 Class 被加载 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = newRootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); }
// Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } }
// Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. // 下面这块代码是为了解决循环依赖的问题,这是个重头戏,解决循环依赖问题 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); }
// Initializethebeaninstance. ObjectexposedObject = bean; try { // 这一步也是非常关键的,这一步负责属性装配,因为前面的实例只是实例化了,并没有设值,这里就是设值*************** populateBean(beanName, mbd, instanceWrapper); // 还记得 init-method 吗?还有 InitializingBean 接口?还有 BeanPostProcessor 接口? // 这里就是处理 bean 初始化完成后的各种回调************** exposedObject = initializeBean(beanName, exposedObject, mbd); } catch(Throwable ex) { if(ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw(BeanCreationException)ex; } else { thrownewBeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } // 下面这块代码是为了解决循环依赖的问题,这是个重头戏,解决循环依赖问题 if(earlySingletonExposure) { //循环依赖的核心方法调用 ObjectearlySingletonReference = getSingleton(beanName, false); if(earlySingletonReference != null) { if(exposedObject == bean) { exposedObject = earlySingletonReference; } elseif(!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = newLinkedHashSet<>(dependentBeans.length); for(String dependentBean : dependentBeans) { if(!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if(!actualDependentBeans.isEmpty()) { thrownewBeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); } } } }
/** Cache of singleton objects: bean name to bean instance. */ //单例对象的cache privatefinal Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */ // 单例对象工厂的cache privatefinal Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */ //提前曝光的单例对象的Cache privatefinal Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { // Make sure bean class is actually resolved at this point. // 确保已经加载了此 class Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 校验一下这个类的访问权限 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw newBeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); }
protectedvoidpopulateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { if (bw == null) { if (mbd.hasPropertyValues()) { thrownewBeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. return; } }
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessoribp= (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } }
intresolvedAutowireMode= mbd.getResolvedAutowireMode(); // 通过名字找到所有属性值,如果是 bean 依赖,先初始化依赖的 bean。记录依赖关系 if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { MutablePropertyValuesnewPvs=newMutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; }