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);}}}}
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);// 初始化bean
exposedObject =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);}}}