DefaultListableBeanFactory類
publicvoidpreInstantiateSingletons()throwsBeansException{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.List<String> beanNames =newArrayList<>(this.beanDefinitionNames);// Trigger initialization of all non-lazy singleton beans...for(String beanName : beanNames){RootBeanDefinition bd =getMergedLocalBeanDefinition(beanName);// 是非抽象的并且是單例的并且不是懶加載的if(!bd.isAbstract()&& bd.isSingleton()&&!bd.isLazyInit()){// 如果是FactoryBean執行下面邏輯(如果是實現了FactoryBean,isFactoryBean的標識為true)if(isFactoryBean(beanName)){Object bean =getBean(FACTORY_BEAN_PREFIX+ beanName);// beanName = & + beanNameif(bean instanceofFactoryBean){FactoryBean<?> factory =(FactoryBean<?>) bean;boolean isEagerInit;if(System.getSecurityManager()!=null&& factory instanceofSmartFactoryBean){isEagerInit =AccessController.doPrivileged((PrivilegedAction<Boolean>)((SmartFactoryBean<?>) factory)::isEagerInit,getAccessControlContext());}else{isEagerInit =(factory instanceofSmartFactoryBean&&((SmartFactoryBean<?>) factory).isEagerInit());}if(isEagerInit){getBean(beanName);}}}else{// 不是FactoryBean執行下面邏輯,普通的單實例非懶加載beangetBean(beanName);}}}}
protected<T>TdoGetBean(String name,@NullableClass<T> requiredType,@NullableObject[] args,boolean typeCheckOnly)throwsBeansException{//處理別名BeanName、處理帶&符的工廠BeanName,工廠beanName帶了&xxx 最后會變成xxxString beanName =transformedBeanName(name);Object beanInstance;// Eagerly check singleton cache for manually registered singletons.// 先檢查單實例bean緩存Object sharedInstance =getSingleton(beanName);if(sharedInstance !=null&& args ==null){if(logger.isTraceEnabled()){if(isSingletonCurrentlyInCreation(beanName)){logger.trace("Returning eagerly cached instance of singleton bean '"+ beanName +"' that is not fully initialized yet - a consequence of a circular reference");}else{logger.trace("Returning cached instance of singleton bean '"+ beanName +"'");}}beanInstance =getObjectForBeanInstance(sharedInstance, name, beanName,null);}else{//默認第一次獲取組件都會進入到else環節,如果第一次獲取肯定是沒有的// Fail if we're already creating this bean instance:// We're assumably within a circular reference.// 如果是一個多實例bean,拋出異常if(isPrototypeCurrentlyInCreation(beanName)){thrownewBeanCurrentlyInCreationException(beanName);}// 拿到整個bean工廠,拿到父工廠;看父工廠有沒有,如果有從父工廠去獲取 Check if bean definition exists in this factory.BeanFactory parentBeanFactory =getParentBeanFactory();if(parentBeanFactory !=null&&!containsBeanDefinition(beanName)){// Not found -> check parent.String nameToLookup =originalBeanName(name);if(parentBeanFactory instanceofAbstractBeanFactory){return((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);}elseif(args !=null){// Delegation to parent with explicit args.return(T) parentBeanFactory.getBean(nameToLookup, args);}elseif(requiredType !=null){// No args -> delegate to standard getBean method.return parentBeanFactory.getBean(nameToLookup, requiredType);}else{return(T) parentBeanFactory.getBean(nameToLookup);}}if(!typeCheckOnly){// 標記當前bean已經被創建,用來阻止多線程引用的markBeanAsCreated(beanName);}StartupStep beanCreation =this.applicationStartup.start("spring.beans.instantiate").tag("beanName", name);try{if(requiredType !=null){beanCreation.tag("beanType", requiredType::toString);}RootBeanDefinition mbd =getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.String[] dependsOn = mbd.getDependsOn();if(dependsOn !=null){// 看有沒有依賴其他Bean,如果有先獲取其他的那個Beanfor(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. 創建Bean試連if(mbd.isSingleton()){sharedInstance =getSingleton(beanName,()->{try{returncreateBean(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是否是使用了beanFactorybeanInstance =getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}elseif(mbd.isPrototype()){// It's a prototype -> create a new instance.Object prototypeInstance =null;try{beforePrototypeCreation(beanName);prototypeInstance =createBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}beanInstance =getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);}else{String scopeName = mbd.getScope();if(!StringUtils.hasLength(scopeName)){thrownewIllegalStateException("No scope name defined for bean ′"+ beanName +"'");}Scope scope =this.scopes.get(scopeName);if(scope ==null){thrownewIllegalStateException("No Scope registered for scope name '"+ scopeName +"'");}try{Object scopedInstance = scope.get(beanName,()->{beforePrototypeCreation(beanName);try{returncreateBean(beanName, mbd, args);}finally{afterPrototypeCreation(beanName);}});beanInstance =getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch(IllegalStateException ex){thrownewScopeNotActiveException(beanName, scopeName, ex);}}}catch(BeansException ex){beanCreation.tag("exception", ex.getClass().toString());beanCreation.tag("message",String.valueOf(ex.getMessage()));cleanupAfterBeanCreationFailure(beanName);throw ex;}finally{beanCreation.end();}}returnadaptBeanInstance(name, beanInstance, requiredType);}
publicObjectgetSingleton(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){thrownewBeanCreationNotAllowedException(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 +"'");}beforeSingletonCreation(beanName);boolean newSingleton =false;boolean recordSuppressedExceptions =(this.suppressedExceptions ==null);if(recordSuppressedExceptions){this.suppressedExceptions =newLinkedHashSet<>();}try{// 會調用lamda表達式的內容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;}afterSingletonCreation(beanName);}if(newSingleton){addSingleton(beanName, singletonObject);}}return singletonObject;}}protectedvoidaddSingleton(String beanName,Object singletonObject){synchronized(this.singletonObjects){this.singletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName);this.earlySingletonObjects.remove(beanName);this.registeredSingletons.add(beanName);}}
protectedObjectdoCreateBean(String beanName,RootBeanDefinition mbd,@NullableObject[] args)throwsBeanCreationException{// Instantiate the bean.BeanWrapper instanceWrapper =null;if(mbd.isSingleton()){//是否單例instanceWrapper =this.factoryBeanInstanceCache.remove(beanName);}if(instanceWrapper ==null){// 創建Bean的實列,默認使用無參構造創建對象instanceWrapper =createBeanInstance(beanName, mbd, args);}Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if(beanType !=NullBean.class){mbd.resolvedTargetType = beanType;}//允許MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition再來修改下BeanDefinition Allow post-processors to modify the merged bean definition.synchronized(mbd.postProcessingLock){if(!mbd.postProcessed){try{applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch(Throwable ex){thrownewBeanCreationException(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));}// Initialize the bean instance.Object exposedObject = bean;try{// 給創建好的對象每個屬性進行賦值,@Autowired發生在這里populateBean(beanName, mbd, instanceWrapper);// 初始化beanexposedObject =initializeBean(beanName, exposedObject, mbd);}catch(Throwable ex){if(ex instanceofBeanCreationException&& beanName.equals(((BeanCreationException) ex).getBeanName())){throw(BeanCreationException) ex;}else{thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Initialization of bean failed", ex);}}if(earlySingletonExposure){Object earlySingletonReference =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.");}}}}// Register bean as disposable.try{registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch(BeanDefinitionValidationException ex){thrownewBeanCreationException(mbd.getResourceDescription(), beanName,"Invalid destruction signature", ex);}return exposedObject;}protectedvoidaddSingletonFactory(String beanName,ObjectFactory<?> singletonFactory){Assert.notNull(singletonFactory,"Singleton factory must not be null");synchronized(this.singletonObjects){if(!this.singletonObjects.containsKey(beanName)){this.singletonFactories.put(beanName, singletonFactory);this.earlySingletonObjects.remove(beanName);this.registeredSingletons.add(beanName);}}}