Spring core 源码分析

    上节提到了在AbstractApplicationContext 调用refresh方法里,初始化所有BeanDefinitions后,遍历所有BeanDefinitionNames后,循环调用BeanFactory的getBean(name)方法,实例化所有容器 Bean对象(非lasy-init)。

GetBean做了什么?循环引用如何处理的?

    既然是BeanFactory的getBean方法,详细看下BeanFactory相关的类图:

  • DefaultListableBeanFactory: ListableBeanFactory和BeanDefinitionRegistry接口的默认实现,也是一个功能完善的BeanFactory,可以作为一个独立的BeanFactory使用,也可作为自定义BeanFactory的父类。
  • ConfigurableListableBeanFactory接口:提供分析和修改BeanDefinition,以及预初始化singletons接口。
  • ListableBeanFactory接口: BeanFactory接口的扩展接口,定义了各种Map<String,Object> getbeans* 的接口。
  • BeanFactory接口:BeanFactory作为最原始同时也最重要的Ioc容器,它主要的功能是为依赖注入 (DI) 提供支持,也是访问bean容器的客户端视角。BeanFactory包含了一系列bean definitions,每一个Bean definitions都有一个字符串的唯一标识。BeanFactory通过Bean definition 返回singleton的(独立的-prototype,request,session)等不同scope的bean实例。
  • AutowireCapableBeanFactory接口:定义了BeanFactory能够使用Autowiring的相关接口。
  • **ConfigurableBeanFactory接口:**提供配置BeanFactory的相关接口。
  • HierachicalBeanFactory接口:接口被bean factoris 实现,实现分层级的bean Factory。
  • SingletonBeanRegistry 接口: 为所有的singleton的bean提供统一的管理机制。
  • AbstractAutowireCapableBeanFactory : 实现了通过RootBeanDefinition创建bean的默认实现,提供bean创建,property populatin,autowring,handles runtime bean references,resolves managed collections,调用初始化方法等实现。
  • AbstractBeanFactory:BeanFactory接口的基础实现抽象类。
  • FactoryBeanRegistrySupport:  FactoryBean实例的管理,以及DefaultSingletonBeanRegistry的管理。
  • DefaultSingletonBeanRegistry: 实现SingletonBeanRegistry接口。
  • SimpleAliasRegistry : 实现 AliasRegistry接口。
  • AliasRegistry接口:别名相关的所有功能。

调用GetBean时,调用时序图如下:

    我们先从AbstractBeanFactory的 doGetBean(final String name,final Class<T> requiredType,final Object[] args,boolean typeCheckOnly) 开始,

参数意义如下:

  • name:需要得到bean的名称
  • requireType:需要得到bean的类型
  • args:创建bean实例时用的更为详细的参数(只在创建bean 实例时起作用)
  • typeCheckOnly:表明这个instance只是为了类型的检查,而不是真正创建一个bean

调用流程如下:

getBean主流程图

源码如下:

1 /** 2 * Return an instance, which may be shared or independent, of the specified bean. 3 * @param name the name of the bean to retrieve 4 * @param requiredType the required type of the bean to retrieve 5 * @param args arguments to use when creating a bean instance using explicit arguments 6 * (only applied when creating a new instance as opposed to retrieving an existing one) 7 * @param typeCheckOnly whether the instance is obtained for a type check, 8 * not for actual use 9 * @return an instance of the bean 10 * @throws BeansException if the bean could not be created 11 */ 12 @SuppressWarnings("unchecked") 13 protected <T> T doGetBean( 14 final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) 15 throws BeansException { 16 //处理name,去除开头&,若是别名则转换成标准beanName 17 final String beanName = transformedBeanName(name); 18 Object bean; 19 20 // Eagerly check singleton cache for manually registered singletons. 21 // 取缓存的Bean,在此处解决了循环引用的问题 22 Object sharedInstance = getSingleton(beanName); 23 if (sharedInstance != null && args == null) { 24 if (logger.isDebugEnabled()) { 25 if (isSingletonCurrentlyInCreation(beanName)) { 26 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + 27 "' that is not fully initialized yet - a consequence of a circular reference"); 28 } 29 else { 30 logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); 31 } 32 } 33 // 完成FactoryBean的处理 34 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); 35 } 36 37 else { 38 // Fail if we're already creating this bean instance: 39 // We're assumably within a circular reference. 40 // 如果我们已经正在创建这个bean实例,则因为循环引用的问题抛出异常 41 if (isPrototypeCurrentlyInCreation(beanName)) { 42 throw new BeanCurrentlyInCreationException(beanName); 43 } 44 45 // Check if bean definition exists in this factory. 46 // 检查bean definition是否在当前beanFactory中,若不在,委派到父类 or 父类的父类 47 BeanFactory parentBeanFactory = getParentBeanFactory(); 48 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { 49 // Not found -> check parent. 50 String nameToLookup = originalBeanName(name); 51 if (args != null) { 52 // Delegation to parent with explicit args. 53 return (T) parentBeanFactory.getBean(nameToLookup, args); 54 } 55 else { 56 // No args -> delegate to standard getBean method. 57 return parentBeanFactory.getBean(nameToLookup, requiredType); 58 } 59 } 60 61 if (!typeCheckOnly) { 62 // 标记bean为已创建,放入alreadyCreated Set<String> 63 markBeanAsCreated(beanName); 64 } 65 66 try { 67 // 通过beanName得到BeanDefinition 68 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); 69 checkMergedBeanDefinition(mbd, beanName, args); 70 71 // Guarantee initialization of beans that the current bean depends on. 72 // 得到目标bean所有依赖的beanNames 73 String[] dependsOn = mbd.getDependsOn(); 74 if (dependsOn != null) { 75 for (String dep : dependsOn) { 76 if (isDependent(beanName, dep)) { 77 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 78 "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); 79 } 80 // 将依赖bean注册到目标bean上,保证在目标bean destroy前被destroy 81 registerDependentBean(dep, beanName); 82 // 创建 dependent的bean实例 83 getBean(dep); 84 } 85 } 86 87 // Create bean instance. 88 // 创建单例模式的bean 89 if (mbd.isSingleton()) { 90 // 使用匿名的内部类,创建一个Bean实例 在 DefaultSingletonBeanRegisty.java中 91 sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { 92 // getSingleton中会调用getObject() 93 @Override 94 public Object getObject() throws BeansException { 95 try { 96 return createBean(beanName, mbd, args); 97 } 98 catch (BeansException ex) { 99 // Explicitly remove instance from singleton cache: It might have been put there 100 // eagerly by the creation process, to allow for circular reference resolution. 101 // Also remove any beans that received a temporary reference to the bean. 102 destroySingleton(beanName); 103 throw ex; 104 } 105 } 106 }); 107 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 108 } 109 // 创建prototype模式的bean 110 else if (mbd.isPrototype()) { 111 // It's a prototype -> create a new instance. 112 Object prototypeInstance = null; 113 try { 114 beforePrototypeCreation(beanName); 115 prototypeInstance = createBean(beanName, mbd, args); 116 } 117 finally { 118 afterPrototypeCreation(beanName); 119 } 120 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); 121 } 122 // 创建其他scope的bean 123 else { 124 String scopeName = mbd.getScope(); 125 final Scope scope = this.scopes.get(scopeName); 126 if (scope == null) { 127 throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); 128 } 129 try { 130 Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { 131 @Override 132 public Object getObject() throws BeansException { 133 beforePrototypeCreation(beanName); 134 try { 135 return createBean(beanName, mbd, args); 136 } 137 finally { 138 afterPrototypeCreation(beanName); 139 } 140 } 141 }); 142 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); 143 } 144 catch (IllegalStateException ex) { 145 throw new BeanCreationException(beanName, 146 "Scope '" + scopeName + "' is not active for the current thread; consider " + 147 "defining a scoped proxy for this bean if you intend to refer to it from a singleton", 148 ex); 149 } 150 } 151 } 152 catch (BeansException ex) { 153 cleanupAfterBeanCreationFailure(beanName); 154 throw ex; 155 } 156 } 157 158 // Check if required type matches the type of the actual bean instance. 159 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { 160 try { 161 return getTypeConverter().convertIfNecessary(bean, requiredType); 162 } 163 catch (TypeMismatchException ex) { 164 if (logger.isDebugEnabled()) { 165 logger.debug("Failed to convert bean '" + name + "' to required type '" + 166 ClassUtils.getQualifiedName(requiredType) + "'", ex); 167 } 168 throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); 169 } 170 } 171 return (T) bean; 172 }

由于大部分业务bean都是singleton的,所以doGetBean方法直接就去看beanFactory的 singletonObjects里有没有目标bean。我们可以详细看下<getBean主流程图> 里第一个子流程

sharedInstance = getSingleton(beanName) ---> 调用:

DefaultSingletonBeanRegistry.java 里的getSingleton(beanName,allowEarlyReference=true) 方法。

流程图:

源码如下:

1 /** 2 * Return the (raw) singleton object registered under the given name. 3 * <p>Checks already instantiated singletons and also allows for an early 4 * reference to a currently created singleton (resolving a circular reference). 5 * @param beanName the name of the bean to look for 6 * @param allowEarlyReference whether early references should be created or not 7 * @return the registered singleton object, or {@code null} if none found 8 */ 9 protected Object getSingleton(String beanName, boolean allowEarlyReference) { 10 Object singletonObject = this.singletonObjects.get(beanName); 11 if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { 12 synchronized (this.singletonObjects) { 13 singletonObject = this.earlySingletonObjects.get(beanName); 14 if (singletonObject == null && allowEarlyReference) { 15 ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); 16 if (singletonFactory != null) { 17 singletonObject = singletonFactory.getObject(); 18 this.earlySingletonObjects.put(beanName, singletonObject); 19 this.singletonFactories.remove(beanName); 20 } 21 } 22 } 23 } 24 return (singletonObject != NULL_OBJECT ? singletonObject : null); 25 }

    若通过BeanName得到singletonObjects里的bean,判断是一个标准bean ,而不是FactoryBean,或者调用方就需要一个FactoryBean的引用,就直接返回。 

    若是取到的sharedInstance为空,那么后续会走双亲委派模型 去搜索父BeanFactory里是否有当前BeanName的BeanDefinition,若有,让父BeanFactory去初始化Bean。

    双亲委派模型,典型的使用就是JVM的类加载机制了,其优点主要是:

    (1) 保证全局一个Bean只被一个BeanFactory加载,避免了重复加载的问题。

    (2) 模型使得Bean随着BeanFactory具备了一种带优先级的层次关系,越基础的Bean,越会被上层的BeanFactory加载。

    确定了当前bean属于当前的BeanFactory后,加载此Bean的所有depends-on的beans。 当depends-on的beans全被加载完毕后,判断当前bean的scope是哪种?

    spring中的bean的scope有如下几种 singleton(ioc容器里唯一),prototype(每次创建新实例),request(一次http request唯一),session,globalSession,application,websocket 。

    代码中的处理逻辑,做了三个分支, isSingleton,isPrototype,以及其他。

    当bean的scope为Singleton时,会调用父类DefaultSingletonBeanRegistry里的

getSingleton(beanName,ObjectFactory<?>)方法,调用方式如下:

1 // Create bean instance. 2 if (mbd.isSingleton()) { 3 sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { 4 @Override 5 public Object getObject() throws BeansException { 6 try { 7 //createBean其他scope都会调用,而此处getSingleton保证了所有singleton的逻辑 8 return createBean(beanName, mbd, args); 9 } 10 catch (BeansException ex) { 11 // Explicitly remove instance from singleton cache: It might have been put there 12 // eagerly by the creation process, to allow for circular reference resolution. 13 // Also remove any beans that received a temporary reference to the bean. 14 destroySingleton(beanName); 15 throw ex; 16 } 17 } 18 }); 19 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 20 }

DefaultSingletonBeanRegistry.java -----getSingleton(beanName,ObjectFactory<?>) 

流程图如下:

源码如下:

1/** 2 * Return the (raw) singleton object registered under the given name, 3 * creating and registering a new one if none registered yet. 4 * @param beanName the name of the bean 5 * @param singletonFactory the ObjectFactory to lazily create the singleton 6 * with, if necessary 7 * @return the registered singleton object 8 */ 9 public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { 10 Assert.notNull(beanName, "'beanName' must not be null"); 11 synchronized (this.singletonObjects) { 12 Object singletonObject = this.singletonObjects.get(beanName); 13 // 若singletonObjects(Cache of singleton objects)没有beanName,bean没被创建过 14 if (singletonObject == null) { 15 // 标识是否正在 destroy singletons 16 if (this.singletonsCurrentlyInDestruction) { 17 throw new BeanCreationNotAllowedException(beanName, 18 "Singleton bean creation not allowed while singletons of this factory are in destruction " + 19 "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); 20 } 21 if (logger.isDebugEnabled()) { 22 logger.debug("Creating shared instance of singleton bean '" + beanName + "'"); 23 } 24 // 判断是否正在创建,若正在(singletonsCurrentlyInCreation.contains),抛出异常,若不在加入 singletonsCurrentlyInCreation Set<String> 里 25 beforeSingletonCreation(beanName); 26 boolean newSingleton = false; 27 boolean recordSuppressedExceptions = (this.suppressedExceptions == null); 28 if (recordSuppressedExceptions) { 29 this.suppressedExceptions = new LinkedHashSet<Exception>(); 30 } 31 try { 32 // 在此调用上层方法,createBean() 也是创建对象的方法 33 singletonObject = singletonFactory.getObject(); 34 newSingleton = true; 35 } 36 catch (IllegalStateException ex) { 37 // Has the singleton object implicitly appeared in the meantime -> 38 // if yes, proceed with it since the exception indicates that state. 39 singletonObject = this.singletonObjects.get(beanName); 40 if (singletonObject == null) { 41 throw ex; 42 } 43 } 44 catch (BeanCreationException ex) { 45 if (recordSuppressedExceptions) { 46 for (Exception suppressedException : this.suppressedExceptions) { 47 ex.addRelatedCause(suppressedException); 48 } 49 } 50 throw ex; 51 } 52 finally { 53 if (recordSuppressedExceptions) { 54 this.suppressedExceptions = null; 55 } 56 // 创建结束,移除singletonsCurrentlyInCreation里的beanName 57 afterSingletonCreation(beanName); 58 } 59 // 创建成功 60 if (newSingleton) { 61 // 将bean放入singletonObjects里,从singletonFactories里移除beanName, 62 // 从earlySingletonObjects(解决循环依赖,提前引用)中移除, 63 // 添加beanName 到registerdSingletons里 64 addSingleton(beanName, singletonObject); 65 } 66 } 67 return (singletonObject != NULL_OBJECT ? singletonObject : null); 68 } 69 }

调用singletonFactory.getObject() ,即是调用AbstractAutowireCapableBeanFactory的createBean方法。

AbstractAutowireCapableBeanFactory.java---------createBean()

流程图如下:

源码如下:

1 /** 2 * Central method of this class: creates a bean instance, 3 * populates the bean instance, applies post-processors, etc. 4 * @see #doCreateBean 5 */ 6 @Override 7 protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException { 8 if (logger.isDebugEnabled()) { 9 logger.debug("Creating instance of bean '" + beanName + "'"); 10 } 11 RootBeanDefinition mbdToUse = mbd; 12 13 // Make sure bean class is actually resolved at this point, and 14 // clone the bean definition in case of a dynamically resolved Class 15 // which cannot be stored in the shared merged bean definition. 16 // 确保目标bean的class已经被解析并set到beanDefinition里,返回class 17 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); 18 if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { 19 // dynamically resolved Class 不能存储到shared mergedBeanDefinitions 里,所以deep copy 20 mbdToUse = new RootBeanDefinition(mbd); 21 mbdToUse.setBeanClass(resolvedClass); 22 } 23 24 // Prepare method overrides. 25 try { 26 mbdToUse.prepareMethodOverrides(); 27 } 28 catch (BeanDefinitionValidationException ex) { 29 throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), 30 beanName, "Validation of method overrides failed", ex); 31 } 32 33 try { 34 // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. 35 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); 36 if (bean != null) { 37 return bean; 38 } 39 } 40 catch (Throwable ex) { 41 throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, 42 "BeanPostProcessor before instantiation of bean failed", ex); 43 } 44 // 核心创建bean 方法 45 Object beanInstance = doCreateBean(beanName, mbdToUse, args); 46 if (logger.isDebugEnabled()) { 47 logger.debug("Finished creating instance of bean '" + beanName + "'"); 48 } 49 return beanInstance; 50 }

 上述代码调用了 AbstractAutowireCapableBeanFactory的doCreateBean方法:

流程图如下:

源码如下:

1 /** 2 * Actually create the specified bean. Pre-creation processing has already happened 3 * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks. 4 * <p>Differentiates between default bean instantiation, use of a 5 * factory method, and autowiring a constructor. 6 * @param beanName the name of the bean 7 * @param mbd the merged bean definition for the bean 8 * @param args explicit arguments to use for constructor or factory method invocation 9 * @return a new instance of the bean 10 * @throws BeanCreationException if the bean could not be created 11 * @see #instantiateBean 12 * @see #instantiateUsingFactoryMethod 13 * @see #autowireConstructor 14 */ 15 protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) 16 throws BeanCreationException { 17 18 // Instantiate the bean. 19 // beanWrapper 是 low-level 的javaBeans 的结构,可以操作一些bean的属性 20 BeanWrapper instanceWrapper = null; 21 if (mbd.isSingleton()) { 22 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); 23 } 24 if (instanceWrapper == null) { 25 // 创建制定bean新的实例,选用合适的构造方法调用 26 instanceWrapper = createBeanInstance(beanName, mbd, args); 27 } 28 final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); 29 Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); 30 mbd.resolvedTargetType = beanType; 31 32 // Allow post-processors to modify the merged bean definition. 33 synchronized (mbd.postProcessingLock) { 34 if (!mbd.postProcessed) { 35 try { 36 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 37 } 38 catch (Throwable ex) { 39 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 40 "Post-processing of merged bean definition failed", ex); 41 } 42 mbd.postProcessed = true; 43 } 44 } 45 46 // Eagerly cache singletons to be able to resolve circular references 47 // even when triggered by lifecycle interfaces like BeanFactoryAware. 48 // 尽早拿到引用,防止循环引用 49 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && 50 isSingletonCurrentlyInCreation(beanName)); 51 if (earlySingletonExposure) { 52 if (logger.isDebugEnabled()) { 53 logger.debug("Eagerly caching bean '" + beanName + 54 "' to allow for resolving potential circular references"); 55 } 56 addSingletonFactory(beanName, new ObjectFactory<Object>() { 57 @Override 58 public Object getObject() throws BeansException { 59 return getEarlyBeanReference(beanName, mbd, bean); 60 } 61 }); 62 } 63 64 // Initialize the bean instance. 65 Object exposedObject = bean; 66 try { 67 // 给Bean的属性赋值,属性的依赖在此注入 68 populateBean(beanName, mbd, instanceWrapper); 69 if (exposedObject != null) { 70 // 初始化bean对象 71 exposedObject = initializeBean(beanName, exposedObject, mbd); 72 } 73 } 74 catch (Throwable ex) { 75 if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { 76 throw (BeanCreationException) ex; 77 } 78 else { 79 throw new BeanCreationException( 80 mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); 81 } 82 } 83 // 若bean是singleton 并且正在创建 84 if (earlySingletonExposure) { 85 Object earlySingletonReference = getSingleton(beanName, false); 86 if (earlySingletonReference != null) { 87 // 正在实例化的bean 和目标bean是一个 88 if (exposedObject == bean) { 89 exposedObject = earlySingletonReference; 90 } 91 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { 92 String[] dependentBeans = getDependentBeans(beanName); 93 Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length); 94 for (String dependentBean : dependentBeans) { 95 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { 96 actualDependentBeans.add(dependentBean); 97 } 98 } 99 if (!actualDependentBeans.isEmpty()) { 100 throw new BeanCurrentlyInCreationException(beanName, 101 "Bean with name '" + beanName + "' has been injected into other beans [" + 102 StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + 103 "] in its raw version as part of a circular reference, but has eventually been " + 104 "wrapped. This means that said other beans do not use the final version of the " + 105 "bean. This is often the result of over-eager type matching - consider using " + 106 "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); 107 } 108 } 109 } 110 } 111 112 // Register bean as disposable. 113 try { 114 registerDisposableBeanIfNecessary(beanName, bean, mbd); 115 } 116 catch (BeanDefinitionValidationException ex) { 117 throw new BeanCreationException( 118 mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); 119 } 120 121 return exposedObject; 122 }

BeanWrapper接口提供一系列对Bean中属性 set get 以及 converter等功能。

可以看到instanceWrapper是由AbstractAutowiredCapableBeanFactory 的createBeanInstance方法创建,

流程图如下:

1/** 2 * Create a new instance for the specified bean, using an appropriate instantiation strategy: 3 * factory method, constructor autowiring, or simple instantiation. 4 * @param beanName the name of the bean 5 * @param mbd the bean definition for the bean 6 * @param args explicit arguments to use for constructor or factory method invocation 7 * @return BeanWrapper for the new instance 8 * @see #instantiateUsingFactoryMethod 9 * @see #autowireConstructor 10 * @see #instantiateBean 11 */ 12 protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { 13 // Make sure bean class is actually resolved at this point. 14 Class<?> beanClass = resolveBeanClass(mbd, beanName); 15 16 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { 17 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 18 "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); 19 } 20 21 if (mbd.getFactoryMethodName() != null) { 22 return instantiateUsingFactoryMethod(beanName, mbd, args); 23 } 24 25 // Shortcut when re-creating the same bean... 26 boolean resolved = false; 27 boolean autowireNecessary = false; 28 if (args == null) { 29 synchronized (mbd.constructorArgumentLock) { 30 if (mbd.resolvedConstructorOrFactoryMethod != null) { 31 resolved = true; 32 autowireNecessary = mbd.constructorArgumentsResolved; 33 } 34 } 35 } 36 if (resolved) { 37 if (autowireNecessary) { 38 return autowireConstructor(beanName, mbd, null, null); 39 } 40 else { 41 return instantiateBean(beanName, mbd); 42 } 43 } 44 45 // Need to determine the constructor... 46 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); 47 if (ctors != null || 48 mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR || 49 mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { 50 return autowireConstructor(beanName, mbd, ctors, args); 51 } 52 53 // No special handling: simply use no-arg constructor. 54 return instantiateBean(beanName, mbd); 55 }

    从上述代码中,可以看到有三种初始化BeanWrapper的方式,

    (1) instantiateUsingFactoryMethod ---- 当BeanDefinition有工厂方法时

    (2) autowireConstructor ------ 当BeanDefinition有构造函数 或者 args 不为空 等

    (3) instantiateBean ------ 无参时默认构造函数

    三者都调用了 beanFactory.getInstantiationStrategy.instantiate()

    

    默认实现使用了Cglib :

1 /** 2 * Create a new instance of a dynamically generated subclass implementing the 3 * required lookups. 4 * @param ctor constructor to use. If this is {@code null}, use the 5 * no-arg constructor (no parameterization, or Setter Injection) 6 * @param args arguments to use for the constructor. 7 * Ignored if the {@code ctor} parameter is {@code null}. 8 * @return new instance of the dynamically generated subclass 9 */ 10 public Object instantiate(Constructor<?> ctor, Object... args) { 11 Class<?> subclass = createEnhancedSubclass(this.beanDefinition); 12 Object instance; 13 if (ctor == null) { 14 instance = BeanUtils.instantiateClass(subclass); 15 } 16 else { 17 try { 18 Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes()); 19 instance = enhancedSubclassConstructor.newInstance(args); 20 } 21 catch (Exception ex) { 22 throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), 23 "Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex); 24 } 25 } 26 // SPR-10785: set callbacks directly on the instance instead of in the 27 // enhanced class (via the Enhancer) in order to avoid memory leaks. 28 Factory factory = (Factory) instance; 29 factory.setCallbacks(new Callback[] {NoOp.INSTANCE, 30 new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner), 31 new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)}); 32 return instance; 33 }

至此,getBean()的所有过程已详尽描述。

getBean的创建流程,可以从整个调用过程中里的一些关键变量的角度来看这个问题:

AbstractBeanFactory----此层面定义的变量用来控制整个BeanFactory:

**List<BeanPostProcessor> beanPostProcessors:**createBean时作用的BeanPostProcessors

Map<String,RootBeanDefinition> mergedBeanDefinitions: bean名称与RBD对应的map

**Set<String> alreadyCreated :**已经至少创建一次的BeanName

ThreadLocal<Object> prototypesCurrentlyInCreation: 正在创建的bean的名称

DefaultSingletonBeanRegistry:

**Map<String,Object> singletonObjects:**ConcurrentHashMap,所有singleton对象,beanName->bean instance

**Map<String,ObjectFactory<?>> singletonFactories:**singleton工厂对象,beanName->ObjectFactory

Map<String,Object> earlySingletonObjects : 早期的singleton对象。

Set<String> registeredSingletons : 注册的singletons的集合,包含正在注册序列的bean names

Set<String> singletonCurrentlyInCreation : 当前正在创建的bean的names

Set<String> inCreationCheckExclusions : 创建检查之外的Bean的names

Map<String,Object> disposableBeans : beanName -> disposable bean 实例 

Map<String,Set<String>> containedBeanMap: bean包含的bean names的map

Map<String,Set<String>> dependentBeanMap: bean 和 依赖的bean names的map

Map<String,Set<String>> dependeciesForBeanMap : bean 和 引用它的bean names 的map

1.在AbstractBeanFactory---doGetBean里 getSingleton(beanName)里会先看singletonObjects是否有这个Bean,若没有,再看singletonsCurrentlyInCreation里有没有这个Bean。若有,再看earlySingletonObjects里是否有这个Bean,若有直接返回,若没有,再看singletonFactories是否有这个BeanName,若有则创建这个bean,并将其放入 earlySingletonObjects里。

从此过程可以看出 一个Bean 从 ObjectFactory ---> earlySingletonObject -> 完整的Bean的。

下一遍会详细说明Spring 中的循环引用是如何处理的?

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )