spring bean 的实例化过程
调用链路图 简单链路图
详细链路图:
调用链 比如我们容器中 A a = tcx.getBean(A.class); 容器中的过程是什么?
I1…org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)
I2…org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
I2.1…org.springframework.beans.factory.support.AbstractBeanFactory#transformedBeanName转换 beanName
I2.2…org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton去缓存 中获取bean
I2.3…org.springframework.beans.factory.support.AbstractBeanFactory#getObjectForBeanInstance 对缓存中的获取的bean进行后续处理
I2.4…org.springframework.beans.factory.support.AbstractBeanFactory#isPrototypeCurrentlyInCreation 判断原型bean的依赖注入
I2,5…org.springframework.beans.factory.support.AbstractBeanFactory#getParentBeanFactory 检查父容器加载bean
I2.6…org.springframework.beans.factory.support.AbstractBeanFactory#getMergedLocalBeanDefinition 将bean定义转为RootBeanDifination
I2.7…org.springframework.beans.factory.support.AbstractBeanFactory#checkMergedBeanDefinition 检查bean的依赖(bean加载顺序的依赖)
I2.8…org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton 根据
scope 的添加来创建bean
i3…org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean 创建 bean的方法
i4…org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean 真正的创建bean的逻辑
i4.1…org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance 调用构造函数创建对象
i4.2…判断是否需要提早暴露对象(mbd.isSingleton() && this.allowCircularReferences && i
sSingletonCurrentlyInCreation(beanName));
i4.3…org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletonFactory 暴露对象解决循环依赖
i4.4…org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean 给创建的bean进行赋值
i4.5…org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean 对象进行初始化
i4.5.1…org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods 调用XXAware接口
i4.5.2…org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization 调用bean的后置处理器进行对处理
i4.5.3…org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods 对象的初始化方法
i4.5.3.1…org.springframework.beans.factory.InitializingBean#afterPropertiesSet 调用 InitializingBean的方法
i4.5.3.2…String initMethodName = mbd.getInitMethodName(); 自定义的初始化方法
i5…org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingleton 把创建好的实 例化好的bean加载缓存中
I6…org.springframework.beans.factory.support.AbstractBeanFactory#getObjectForBeanInstance 对创建的bean进行后续的加工
源码分析 i1 getBean i1 org.springframework.beans.factory.support.AbstractBeanFactory#getBean
1 2 3 public Object getBean (String name) throws BeansException { return doGetBean(name, null , null , false ); }
I2 doGetBean I2 org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 protected <T> T doGetBean (String name, Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = this .transformedBeanName(name); Object bean; Object sharedInstance = this .getSingleton(beanName); if (sharedInstance != null && args == null ) { ... bean = this .getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null ); } else { if (this .isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } BeanFactory parentBeanFactory = this .getParentBeanFactory(); if (parentBeanFactory != null && !this .containsBeanDefinition(beanName)) { String nameToLookup = this .originalBeanName(name); if (args != null ) { return parentBeanFactory.getBean(nameToLookup, args); } return parentBeanFactory.getBean(nameToLookup, requiredType); } if (!typeCheckOnly) { this .markBeanAsCreated(beanName); } try { final RootBeanDefinition mbd=this .getMergedLocalBeanDefinition(beanName); this .checkMergedBeanDefinition(mbd, beanName, args); String[] dependsOn = mbd.getDependsOn(); String[] var11; if (dependsOn != null ) { var11 = dependsOn; int var12 = dependsOn.length; for (int var13 = 0 ; var13 < var12; ++var13) { String dep = var11[var13]; this .registerDependentBean(dep, beanName); try { this .getBean(dep); } catch (NoSuchBeanDefinitionException var24) { throw new BeanCreationException(...); } } } if (mbd.isSingleton()) { sharedInstance = this .getSingleton(beanName, new ObjectFactory<Object>() { public Object getObject () throws BeansException { try { return AbstractBeanFactory.this .createBean(beanName, mbd, args); } catch (BeansException var2) { AbstractBeanFactory.this .destroySingleton(beanName); throw var2; } } }); bean = this .getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } else if (mbd.isPrototype()) { var11 = null ; Object prototypeInstance; try { this .beforePrototypeCreation(beanName); prototypeInstance = this .createBean(beanName, mbd, args); } finally { this .afterPrototypeCreation(beanName); } bean = this .getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); Scope scope = (Scope)this .scopes.get(scopeName); try { Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { public Object getObject () throws BeansException { AbstractBeanFactory.this .beforePrototypeCreation(beanName); Object var1; try { var1 = AbstractBeanFactory.this .createBean(beanName, mbd, args); } finally { AbstractBeanFactory.this .afterPrototypeCreation(beanName); } return var1; } }); bean = this .getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException var23) { throw new BeanCreationException(...); } } } catch (BeansException var26) { this .cleanupAfterBeanCreationFailure(beanName); throw var26; } } if (requiredType != null && bean != null && !requiredType.isInstance(bean)) { try { return this .getTypeConverter().convertIfNecessary(bean, requiredType); } catch (TypeMismatchException var25) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } else { return bean; } }
i2.2 getSingleton i2.2 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton 去缓存中 获取bean源码分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 protected Object getSingleton (String beanName, boolean allowEarlyReference) { Object singletonObject = this .singletonObjects.get(beanName); if (singletonObject == null && this .isSingletonCurrentlyInCreation(beanName)) { Map var4 = this .singletonObjects; synchronized (this .singletonObjects) { singletonObject = this .earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { ObjectFactory<?> singletonFactory = (ObjectFactory)this .singletonFactories.get(beanName); if (singletonFactory != null ) { singletonObject = singletonFactory.getObject(); this .earlySingletonObjects.put(beanName, singletonObject); this .singletonFactories.remove(beanName); } } } } return singletonObject != NULL_OBJECT ? singletonObject : null ; }
i2.3 getObjectForBeanInstance i2.3 org.springframework.beans.factory.support.AbstractBeanFactory#getObjectForBeanInstance 在Bean的生命周期中,
getObjectForBeanInstance方法是频繁使用的方法,无论是从缓存中获取出来的bean还是根据scope创建出来的bean,都要通过该方法进行检查。
1:检查当前bean是否为factoryBean,如果是就需要调用该对象的getObject()方法来返回我们需要的bean对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 protected Object getObjectForBeanInstance (Object beanInstance, String name, String beanName, RootBeanDefinition mbd) { if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(this .transformedBeanName(name), beanInstance.getClass()); } else if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { Object object = null ; if (mbd == null ) { object = this .getCachedObjectForFactoryBean(beanName); } if (object == null ) { FactoryBean<?> factory = (FactoryBean)beanInstance; if (mbd == null && this .containsBeanDefinition(beanName)) { mbd = this .getMergedLocalBeanDefinition(beanName); } boolean synthetic = mbd != null && mbd.isSynthetic(); object = this .getObjectFromFactoryBean(factory, beanName, !synthetic); } return object; } else { return beanInstance; } }
======核心方法===========getObjectFromFactoryBean()方法==
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 protected Object getObjectFromFactoryBean (FactoryBean<?> factory, String beanName, boolean shouldPostProcess) { if (factory.isSingleton() && this .containsSingleton(beanName)) { synchronized (this .getSingletonMutex()) { Object object = this .factoryBeanObjectCache.get(beanName); if (object == null ) { object = this .doGetObjectFromFactoryBean(factory, beanName); Object alreadyThere = this .factoryBeanObjectCache.get(beanName); if (alreadyThere != null ) { object = alreadyThere; } else { if (object != null && shouldPostProcess) { if (this .isSingletonCurrentlyInCreation(beanName)) { return object; } this .beforeSingletonCreation(beanName); try { object = this .postProcessObjectFromFactoryBean(object, beanName); } catch (Throwable var14) { throw new BeanCreationException(beanName, "Post-processing of FactoryBean's singleton object failed" , var14); } finally { this .afterSingletonCreation(beanName); } } if (this .containsSingleton(beanName)) { this .factoryBeanObjectCache.put(beanName, object != null ? object : NULL_OBJECT); } } } return object != NULL_OBJECT ? object : null ; } } else { Object object = this .doGetObjectFromFactoryBean(factory, beanName); if (object != null && shouldPostProcess) { try { object = this .postProcessObjectFromFactoryBean(object, beanName); } catch (Throwable var17) { throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed" , var17); } } return object; } }
=====================================doGetObjectFromFactoryBean()作用====================
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 private Object doGetObjectFromFactoryBean (final FactoryBean<?> factory, String beanName) throws BeanCreationException { Object object; try { if (System.getSecurityManager() != null ) { AccessControlContext acc = this .getAccessControlContext(); try { object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run () throws Exception { return factory.getObject(); } }, acc); } catch (PrivilegedActionException var6) { throw var6.getException(); } } else { object = factory.getObject(); } } catch (FactoryBeanNotInitializedException var7) { throw new BeanCurrentlyInCreationException(beanName, var7.toString()); } catch (Throwable var8) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation" , var8); } if (object == null && this .isSingletonCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName, "FactoryBean which is currently in creation returned null from getObject" ); } else { return object; } }
i2.6 getMergedLocalBeanDefinition i2.6 org.springframework.beans.factory.support.AbstractBeanFactory#getMergedLocalBeanDefinition 将 bean定义转为RootBeanDifination
合并父子bean定义
1 2 3 4 5 6 protected RootBeanDefinition getMergedLocalBeanDefinition (String beanName) throws BeansException { RootBeanDefinition mbd = (RootBeanDefinition)this .mergedBeanDefinitions.get(beanName); return mbd != null ? mbd : this .getMergedBeanDefinition(beanName, this .getBeanDefinition(beanName)); }
======================getMergedBeanDefinition
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 protected RootBeanDefinition getMergedBeanDefinition (String beanName, BeanDefinition bd, BeanDefinition containingBd) throws BeanDefinitionStoreException { Map var4 = this .mergedBeanDefinitions; synchronized (this .mergedBeanDefinitions) { RootBeanDefinition mbd = null ; if (containingBd == null ) { mbd = (RootBeanDefinition)this .mergedBeanDefinitions.get(beanName); } if (mbd == null ) { if (bd.getParentName() == null ) { if (bd instanceof RootBeanDefinition) { mbd = ((RootBeanDefinition)bd).cloneBeanDefinition(); } else { mbd = new RootBeanDefinition(bd); } } else { BeanDefinition pbd; try { String parentBeanName = transformedBeanName(bd.getParentName()); if (!beanName.equals(parentBeanName)) { pbd = this .getMergedBeanDefinition(parentBeanName); } else { BeanFactory parent = this .getParentBeanFactory(); if (!(parent instanceof ConfigurableBeanFactory)) { throw new NoSuchBeanDefinitionException(...); } pbd = ((ConfigurableBeanFactory)parent).getMergedBeanDefinition(parentBeanName); } } catch (NoSuchBeanDefinitionException var10) { throw new BeanDefinitionStoreException(...); } mbd = new RootBeanDefinition(pbd); mbd.overrideFrom(bd); } if (!StringUtils.hasLength(mbd.getScope())) { mbd.setScope("singleton" ); } if (containingBd == null && this .isCacheBeanMetadata()) { this .mergedBeanDefinitions.put(beanName, mbd); } } return mbd; } }
i2.8 getSingleton i2.8 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton根据scope 的添加来创建bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 public Object getSingleton (String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(beanName, "'beanName' must not be null" ); Map var3 = this .singletonObjects; synchronized (this .singletonObjects) { Object singletonObject = this .singletonObjects.get(beanName); if (singletonObject == null ) { if (this .singletonsCurrentlyInDestruction) { throw new BeanCreationNotAllowedException(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 (this .logger.isDebugEnabled()) { this .logger.debug("Creating shared instance of singleton bean '" + beanName + "'" ); } this .beforeSingletonCreation(beanName); boolean newSingleton = false ; boolean recordSuppressedExceptions = this .suppressedExceptions == null ; if (recordSuppressedExceptions) { this .suppressedExceptions = new LinkedHashSet(); } try { singletonObject = singletonFactory.getObject(); newSingleton = true ; } catch (IllegalStateException var16) { singletonObject = this .singletonObjects.get(beanName); if (singletonObject == null ) { throw var16; } } catch (BeanCreationException var17) { BeanCreationException ex = var17; if (recordSuppressedExceptions) { Iterator var8 = this .suppressedExceptions.iterator(); while (var8.hasNext()) { Exception suppressedException = (Exception)var8.next(); ex.addRelatedCause(suppressedException); } } throw ex; } finally { if (recordSuppressedExceptions) { this .suppressedExceptions = null ; } this .afterSingletonCreation(beanName); } if (newSingleton) { this .addSingleton(beanName, singletonObject); } } return singletonObject != NULL_OBJECT ? singletonObject : null ; } }
==============================================addSingleton(beanName, singletonObject);======
1 2 3 4 5 6 7 8 9 10 11 protected void addSingleton (String beanName, Object singletonObject) { Map var3 = this .singletonObjects; synchronized (this .singletonObjects) { this .singletonObjects.put(beanName, singletonObject != null ? singletonObject : NULL_OBJECT); this .singletonFactories.remove(beanName); this .earlySingletonObjects.remove(beanName); this .registeredSingletons.add(beanName); } }
i3 createBean org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 protected Object createBean (String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException { if (this .logger.isDebugEnabled()) { this .logger.debug("Creating instance of bean '" + beanName + "'" ); } RootBeanDefinition mbdToUse = mbd; Class<?> resolvedClass = this .resolveBeanClass(mbd, beanName, new Class[0 ]); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null ) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } try { mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException var7) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed" , var7); } Object beanInstance; try { beanInstance = this .resolveBeforeInstantiation(beanName, mbdToUse); if (beanInstance != null ) { return beanInstance; } } catch (Throwable var8) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed" , var8); } beanInstance = this .doCreateBean(beanName, mbdToUse, args); if (this .logger.isDebugEnabled()) { this .logger.debug("Finished creating instance of bean '" + beanName + "'" ); } return beanInstance; }
i4 doCreateBean org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean 真正 的创建bean的逻辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 protected Object doCreateBean (final String beanName, final RootBeanDefinition mbd, Object[] args) throws BeanCreationException { BeanWrapper instanceWrapper = null ; if (mbd.isSingleton()) { instanceWrapper = (BeanWrapper)this .factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null ) { instanceWrapper = this .createBeanInstance(beanName, mbd, args); } final Object bean = instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null ; Class<?> beanType = instanceWrapper != null ? instanceWrapper.getWrappedClass() : null ; mbd.resolvedTargetType = beanType; Object var7 = mbd.postProcessingLock; synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { this .applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable var17) { throw new BeanCreationException(...); } mbd.postProcessed = true ; } } boolean earlySingletonExposure = mbd.isSingleton() && this .allowCircularReferences && this .isSingletonCurrentlyInCreation(beanName); if (earlySingletonExposure) { if (this .logger.isDebugEnabled()) { this .logger.debug(...); } this .addSingletonFactory(beanName, new ObjectFactory<Object>() { public Object getObject () throws BeansException { return AbstractAutowireCapableBeanFactory.this .getEarlyBeanReference(beanName, mbd, bean); } }); } Object exposedObject = bean; try { this .populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null ) { exposedObject = this .initializeBean(beanName, exposedObject, mbd); } } catch (Throwable var18) { if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) { throw (BeanCreationException)var18; } throw new BeanCreationException(...); } if (earlySingletonExposure) { Object earlySingletonReference = this .getSingleton(beanName, false ); if (earlySingletonReference != null ) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this .allowRawInjectionDespiteWrapping && this .hasDependentBean(beanName)) { String[] dependentBeans = this .getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length); String[] var12 = dependentBeans; int var13 = dependentBeans.length; for (int var14 = 0 ; var14 < var13; ++var14) { String dependentBean = var12[var14]; if (!this .removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(...); } } } } try { this .registerDisposableBeanIfNecessary(beanName, bean, mbd); return exposedObject; } catch (BeanDefinitionValidationException var16) { throw new BeanCreationException(...); } }
i4.1 createBeanInstance org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance
调用构造函数创建对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 protected BeanWrapper createBeanInstance (String beanName, RootBeanDefinition mbd, Object[] args) { Class<?> beanClass = this .resolveBeanClass(mbd, beanName, new Class[0 ]); if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } else if (mbd.getFactoryMethodName() != null ) { return this .instantiateUsingFactoryMethod(beanName, mbd, args); } else { boolean resolved = false ; boolean autowireNecessary = false ; if (args == null ) { Object var7 = mbd.constructorArgumentLock; synchronized (mbd.constructorArgumentLock) { if (mbd.resolvedConstructorOrFactoryMethod != null ) { resolved = true ; autowireNecessary = mbd.constructorArgumentsResolved; } } } if (resolved) { return autowireNecessary ? this .autowireConstructor(beanName, mbd, (Constructor[])null , (Object[])null ) : this .instantiateBean(beanName, mbd); } else { Constructor<?>[] ctors = this .determineConstructorsFromBeanPostProcessors(beanClass, beanName); return ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args) ? this .instantiateBean(beanName, mbd) : this .autowireConstructor(beanName, mbd, ctors, args); } } }
=======================================提前暴露对象================================
1 2 3 4 5 6 7 8 9 10 11 12 13 protected void addSingletonFactory (String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(singletonFactory, "Singleton factory must not be null" ); Map var3 = this .singletonObjects; synchronized (this .singletonObjects) { if (!this .singletonObjects.containsKey(beanName)) { this .singletonFactories.put(beanName, singletonFactory); this .earlySingletonObjects.remove(beanName); this .registeredSingletons.add(beanName); } } }
i4.2>:判断是否需要提早暴露对象(mbd.isSingleton() && this.allowCircularReferences && i sSingletonCurrentlyInCreation(beanName));
i4.3 addSingletonFactory org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletonFactory
暴露对象解决循环依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 boolean earlySingletonExposure = (mbd.isSingleton() && this .allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { addSingletonFactory(beanName, new ObjectFactory<Object>() { @Override public Object getObject () throws BeansException { return getEarlyBeanReference(beanName, mbd, bean); } }); } protected void addSingletonFactory (String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(singletonFactory, "Singleton factory must not be null" ); Map var3 = this .singletonObjects; synchronized (this .singletonObjects) { if (!this .singletonObjects.containsKey(beanName)) { this .singletonFactories.put(beanName, singletonFactory); this .earlySingletonObjects.remove(beanName); this .registeredSingletons.add(beanName); } } }
i4.4 populateBean org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean 给 创建的bean进行赋值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 protected void populateBean (String beanName, RootBeanDefinition mbd, BeanWrapper bw) { PropertyValues pvs = mbd.getPropertyValues(); if (bw == null ) { if (!((PropertyValues)pvs).isEmpty()) { throw new BeanCreationException(...); } } else { boolean continueWithPropertyPopulation = true ; if (!mbd.isSynthetic() && this .hasInstantiationAwareBeanPostProcessors()) { Iterator var6 = this .getBeanPostProcessors().iterator(); while (var6.hasNext()) { BeanPostProcessor bp = (BeanPostProcessor)var6.next(); if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { continueWithPropertyPopulation = false ; break ; } } } } if (continueWithPropertyPopulation) { if (mbd.getResolvedAutowireMode() == 1 || mbd.getResolvedAutowireMode() == 2 ) { MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs); if (mbd.getResolvedAutowireMode() == 1 ) { this .autowireByName(beanName, mbd, bw, newPvs); } if (mbd.getResolvedAutowireMode() == 2 ) { this .autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = this .hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = mbd.getDependencyCheck() != 0 ; if (hasInstAwareBpps || needsDepCheck) { PropertyDescriptor[] filteredPds = this .filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); if (hasInstAwareBpps) { Iterator var9 = this .getBeanPostProcessors().iterator(); while (var9.hasNext()) { BeanPostProcessor bp = (BeanPostProcessor)var9.next(); if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp; pvs = ibp.postProcessPropertyValues((PropertyValues)pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null ) { return ; } } } } if (needsDepCheck) { this .checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs); } } this .applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs); } } } 1 )获取了bw的属性列表 2 )在属性列表中被填充的之前,通过InstantiationAwareBeanPostProcessor 对bw的属性进行修改 3 )判断自动装配模型来判断是调用byTypeh还是byName 4 )再次应用后置处理,用于动态修改属性列表 pvs 的内容5 )把属性设置到bw中
i4.5 initializeBean i4.5>org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean对 bean进行初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 protected Object initializeBean (final String beanName, final Object bean, RootBeanDefinition mbd) { if (System.getSecurityManager() != null ) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run () { AbstractAutowireCapableBeanFactory.this .invokeAwareMethods(beanName, bean); return null ; } }, this .getAccessControlContext()); } else { this .invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { wrappedBean = this .applyBeanPostProcessorsBeforeInitialization(bean, beanName); } try { this .invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable var6) { throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null , beanName, "Invocation of init method failed" , var6); } if (mbd == null || !mbd.isSynthetic()) { wrappedBean = this .applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
i4.5.1invokeAwareMethods i4.5.1>:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods 调用XXAware接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 private void invokeAwareMethods (String beanName, Object bean) { if (bean instanceof Aware) { if (bean instanceof BeanNameAware) { ((BeanNameAware)bean).setBeanName(beanName); } if (bean instanceof BeanClassLoaderAware) { ((BeanClassLoaderAware)bean).setBeanClassLoader(this .getBeanClassLoader()); } if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware)bean).setBeanFactory(this ); } } }
i4.5.2 applyBeanPostProcessorsBeforeInitialization org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization 调用bean的后置处理器进行对处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public Object applyBeanPostProcessorsBeforeInitialization (Object existingBean, String beanName) throws BeansException { Object result = existingBean; Iterator var4 = this .getBeanPostProcessors().iterator(); do { if (!var4.hasNext()) { return result; } BeanPostProcessor processor = (BeanPostProcessor)var4.next(); result = processor.postProcessBeforeInitialization(result, beanName); } while (result != null ); return result; }
i4.5.3 invokeInitMethods org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods 对象的实例化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 protected void invokeInitMethods (String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { boolean isInitializingBean = bean instanceof InitializingBean; if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet" ))) { if (this .logger.isDebugEnabled()) { this .logger.debug(...); } if (System.getSecurityManager() != null ) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run () throws Exception { ((InitializingBean)bean).afterPropertiesSet(); return null ; } }, this .getAccessControlContext()); } catch (PrivilegedActionException var6) { throw var6.getException(); } } else { ((InitializingBean)bean).afterPropertiesSet(); } }DefaultSingletonBeanRegistry if (mbd != null ) { String initMethodName = mbd.getInitMethodName(); if (initMethodName != null && (!isInitializingBean || !"afterPropertiesSet" .equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { this .invokeCustomInitMethod(beanName, bean, mbd); } } }
i5 addSingleton org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingleton 把创建好的实 例化好的bean加载缓存中
1 2 3 4 5 6 7 8 9 protected void addSingleton (String beanName, Object singletonObject) { Map var3 = this .singletonObjects; synchronized (this .singletonObjects) { this .singletonObjects.put(beanName, singletonObject != null ? singletonObject : NULL_OBJECT); this .singletonFactories.remove(beanName); this .earlySingletonObjects.remove(beanName); this .registeredSingletons.add(beanName); } }
循环依赖解决链路图