Spring源码学习笔记
Posted DarkFuture
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring源码学习笔记相关的知识,希望对你有一定的参考价值。
Spring源码学习笔记(六)
前言--
最近花了些时间看了《Spring源码深度解析》这本书,算是入门了Spring的源码吧。打算写下系列文章,回忆一下书的内容,总结代码的运行流程。推荐那些和我一样没接触过SSH框架源码又想学习的,阅读郝佳编著的《Spring源码深度解析》这本书,会是个很好的入门。
上一篇中我们梳理到 Spring 加载 XML 配置文件, 完成 XML 的解析工作,接下来我们将进入 Spring 加载 bean 的逻辑。
我们使用 Spring 获取 XML 文件中配置的 bean 的方法是 BeanFactory 的 getBean() 方法,我们就以该方法为入口,来看看加载 bean 的过程:
1 public Object getBean(String name) throws BeansException { 2 //第一步: 将处理方法交给了 doGetBean 方法 3 return this.doGetBean(name, (Class)null, (Object[])null, false); 4 }
1 protected <T> T doGetBean(String name, Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { 2 //第一步: 获取 beanName 3 final String beanName = this.transformedBeanName(name); 4 //第二步: 从缓存中获取 或者 从 singletonFactories 中的 ObjectFactory 中获取 5 Object sharedInstance = this.getSingleton(beanName); 6 Object bean; 7 if(sharedInstance != null && args == null) { 8 if(this.logger.isDebugEnabled()) { 9 //第三步: 判断单例是否有循环依赖的情况 10 if(this.isSingletonCurrentlyInCreation(beanName)) { 11 this.logger.debug("Returning eagerly cached instance of singleton bean ‘" + beanName + "‘ that is not fully initialized yet - a consequence of a circular reference"); 12 } else { 13 this.logger.debug("Returning cached instance of singleton bean ‘" + beanName + "‘"); 14 } 15 } 16 //第四步: 返回对应的 Bean 实例 17 bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null); 18 } else { 19 //第五步: 判断原型是否有循环依赖的情况 20 if(this.isPrototypeCurrentlyInCreation(beanName)) { 21 throw new BeanCurrentlyInCreationException(beanName); 22 } 23 //第六步: 从 parentBeanFactory 中获取 bean 实例 24 BeanFactory parentBeanFactory = this.getParentBeanFactory(); 25 if(parentBeanFactory != null && !this.containsBeanDefinition(beanName)) { 26 String nameToLookup = this.originalBeanName(name); 27 if(args != null) { 28 return parentBeanFactory.getBean(nameToLookup, args); 29 } 30 31 return parentBeanFactory.getBean(nameToLookup, requiredType); 32 } 33 34 if(!typeCheckOnly) { 35 this.markBeanAsCreated(beanName); 36 } 37 38 try { 39 //第七步: 将存储 XML 配置文件的 GenericBeanDefinition 转化为 RootBeanDefinition , 若是子 bean, 则一起合并父 bean 的属性 40 final RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName); 41 this.checkMergedBeanDefinition(mbd, beanName, args); 42 //第八步: bean 当中存在依赖, 递归实例化他们 43 String[] dependsOn = mbd.getDependsOn(); 44 String[] var11; 45 if(dependsOn != null) { 46 var11 = dependsOn; 47 int var12 = dependsOn.length; 48 49 for(int var13 = 0; var13 < var12; ++var13) { 50 String dependsOnBean = var11[var13]; 51 if(this.isDependent(beanName, dependsOnBean)) { 52 throw new BeanCreationException("Circular depends-on relationship between ‘" + beanName + "‘ and ‘" + dependsOnBean + "‘"); 53 } 54 55 this.registerDependentBean(dependsOnBean, beanName); 56 this.getBean(dependsOnBean); 57 } 58 } 59 //第九步: 实例化依赖的 bean 之后, 创建 bean 本身, 这里是处理 singleton 类型的 bean 60 if(mbd.isSingleton()) { 61 sharedInstance = this.getSingleton(beanName, new ObjectFactory<Object>() { 62 public Object getObject() throws BeansException { 63 try { 64 return AbstractBeanFactory.this.createBean(beanName, mbd, args); 65 } catch (BeansException var2) { 66 AbstractBeanFactory.this.destroySingleton(beanName); 67 throw var2; 68 } 69 } 70 }); 71 bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd); 72 } else if(mbd.isPrototype()) { 73 var11 = null; 74 75 //第十步: 处理 prototype 类型的 bean 76 Object prototypeInstance; 77 try { 78 this.beforePrototypeCreation(beanName); 79 prototypeInstance = this.createBean(beanName, mbd, args); 80 } finally { 81 this.afterPrototypeCreation(beanName); 82 } 83 84 bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); 85 } else { 86 //第十一步: 指定 scope 实例化 bean 87 String scopeName = mbd.getScope(); 88 Scope scope = (Scope)this.scopes.get(scopeName); 89 if(scope == null) { 90 throw new IllegalStateException("No Scope registered for scope ‘" + scopeName + "‘"); 91 } 92 93 try { 94 Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { 95 public Object getObject() throws BeansException { 96 AbstractBeanFactory.this.beforePrototypeCreation(beanName); 97 98 Object var1; 99 try { 100 var1 = AbstractBeanFactory.this.createBean(beanName, mbd, args); 101 } finally { 102 AbstractBeanFactory.this.afterPrototypeCreation(beanName); 103 } 104 105 return var1; 106 } 107 }); 108 bean = this.getObjectForBeanInstance(scopedInstance, name, beanName, mbd); 109 } catch (IllegalStateException var21) { 110 throw new BeanCreationException(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", var21); 111 } 112 } 113 } catch (BeansException var23) { 114 this.cleanupAfterBeanCreationFailure(beanName); 115 throw var23; 116 } 117 } 118 119 if(requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { 120 try { 121 //第十二步: bean 的类型检查 122 return this.getTypeConverter().convertIfNecessary(bean, requiredType); 123 } catch (TypeMismatchException var22) { 124 if(this.logger.isDebugEnabled()) { 125 this.logger.debug("Failed to convert bean ‘" + name + "‘ to required type [" + ClassUtils.getQualifiedName(requiredType) + "]", var22); 126 } 127 128 throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); 129 } 130 } else { 131 return bean; 132 } 133 }
bean 的使用是 Spring 框架运行的基本, 所以上啦就一百多行代码也可以理解, 接下来一步一步的深入,了解 Spring 的 bean 的加载过程。
首先, 看看 FactoryBean 这个类,----- 注意: 区分 FactoryBean 和 BeanFactory
1 public interface FactoryBean<T> { 2 //第一步: 返回 FactoryBean 创建的 bean 3 T getObject() throws Exception; 4 //第二步: 返回 创建的 bean 的类型 5 Class<?> getObjectType(); 6 //第三步: 判断 bean 是否单例, 循环依赖的处理只存在单例中,原型直接抛异常 7 boolean isSingleton(); 8 }
认识这个 FactoryBean, 对我们后面理解循环依赖的处理情况有很大的帮助。
在 doGetBean() 方法中, 第二步从缓存中获取 bean 的 getSingleton() 方法的实现逻辑:
1 public Object getSingleton(String beanName) { 2 //第一步: 第二个参数为 true , 允许早期依赖, 也就是从 ObjectFactory 中获取实例 3 return this.getSingleton(beanName, true); 4 }
1 protected Object getSingleton(String beanName, boolean allowEarlyReference) { 2 //第一步: 检查缓存 3 Object singletonObject = this.singletonObjects.get(beanName); 4 //第二步: 处理 缓存没有 且 正在创建的情况 5 if(singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) { 6 Map var4 = this.singletonObjects; 7 synchronized(this.singletonObjects) { 8 singletonObject = this.earlySingletonObjects.get(beanName); 9 //第三步: 若不是正在创建中的 bean, 才进行处理 10 if(singletonObject == null && allowEarlyReference) { 11 ObjectFactory<?> singletonFactory = (ObjectFactory)this.singletonFactories.get(beanName); 12 if(singletonFactory != null) { 13 //第四步: 调用 getObject 方法 14 singletonObject = singletonFactory.getObject(); 15 //第五步: 记录在缓存中 16 this.earlySingletonObjects.put(beanName, singletonObject); 17 this.singletonFactories.remove(beanName); 18 } 19 } 20 } 21 } 22 23 return singletonObject != NULL_OBJECT?singletonObject:null; 24 }
有点晕, 先了解一下缓存 bean 的那几个集合:
1, singletonObjects : 保存 BeanName 和 bean 实例之间的映射;
2, singletonFactories : 保存 BeanName 和 BeanFactory 之间的映射;
3, earlySingletonObjects : 保存 BeanName 和 bean 实例之间的关系, 不同于 singletonObjects, 放在这里的 bean 即使在创建过程中, 其他需要依赖的 bean 也可以通过 getBean() 方法来 获取对应的实例, 目的就是为了检测循环引用;
4, registeredSigletons : 保存已注册的 bean;
记住这几个集合属性的作用, 对后面理解循环依赖至关重要。
在 doGetBean() 方法中, 无论是通过缓存获取, 还是通过 scope 属性获取, 获取到的都只是原始的 bean, 我们需要的是 FactoryBean 中的 getObject() 方法返回的 bean, 而方法 getObjectForBeanInstance() 方法就是处理这个过程的, 其实现逻辑如下:
1 protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, RootBeanDefinition mbd) { 2 //第一步: 是工厂相关的(包含 & 前缀) 且 又不是 FactoryBean类型的, 抛异常 3 if(BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { 4 throw new BeanIsNotAFactoryException(this.transformedBeanName(name), beanInstance.getClass()); 5 } else if(beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { 6 7 Object object = null; 8 if(mbd == null) { 9 //第二步: 从缓存中加载 bean 10 object = this.getCachedObjectForFactoryBean(beanName); 11 } 12 13 if(object == null) { 14 FactoryBean<?> factory = (FactoryBean)beanInstance; 15 if(mbd == null && this.containsBeanDefinition(beanName)) { 16 //第三步: 将 GenericBeanDefinition 转换为 RootBeanDefinition, 若为子 bean, 则合并父 bean 的属性 17 mbd = this.getMergedLocalBeanDefinition(beanName); 18 } 19 20 boolean synthetic = mbd != null && mbd.isSynthetic(); 21 //第四步: 从 Factory 中解析 bean 22 object = this.getObjectFromFactoryBean(factory, beanName, !synthetic); 23 } 24 25 return object; 26 } else { 27 return beanInstance; 28 } 29 }
在 getObjectForBeanInstance() 方法中, 第四步从 Factory 解析 bean 的 getObjectFromFactoryBean() 方法的实现逻辑:
1 protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) { 2 //第一步: 处理单例模式的情况 3 if(factory.isSingleton() && this.containsSingleton(beanName)) { 4 //第二步: 单例的情况下保证全局唯一, 使用缓存策略提高性能 5 synchronized(this.getSingletonMutex()) { 6 Object object = this.factoryBeanObjectCache.get(beanName); 7 if(object == null) { 8 object = this.doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); 9 this.factoryBeanObjectCache.put(beanName, object != null?object:NULL_OBJECT); 10 } 11 12 return object != NULL_OBJECT?object:null; 13 } 14 } else { 15 //第三步: 若不是单例, 则直接调用方法 16 return this.doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); 17 } 18 }
1 private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, String beanName, boolean shouldPostProcess) throws BeanCreationException { 2 Object object; 3 try { 4 //第一步: 权限验证 5 if(System.getSecurityManager() != null) { 6 AccessControlContext acc = this.getAccessControlContext(); 7 8 try { 9 object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { 10 public Object run() throws Exception { 11 //第二步: 调用 FactoryBean 的 getObject() 方法 12 return factory.getObject(); 13 } 14 }, acc); 15 } catch (PrivilegedActionException var8) { 16 throw var8.getException(); 17 } 18 } else { 19 //第三步: 调用 getObject() 方法 20 object = factory.getObject(); 21 } 22 } catch (FactoryBeanNotInitializedException var9) { 23 throw new BeanCurrentlyInCreationException(beanName, var9.toString()); 24 } catch (Throwable var10) { 25 throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", var10); 26 } 27 28 if(object == null && this.isSingletonCurrentlyInCreation(beanName)) { 29 throw new BeanCurrentlyInCreationException(beanName, "FactoryBean which is currently in creation returned null from getObject"); 30 } else { 31 if(object != null && shouldPostProcess) { 32 try { 33 //第四步: 调用后处理器 34 object = this.postProcessObjectFromFactoryBean(object, beanName); 35 } catch (Throwable var7) { 36 throw new BeanCreationException(beanName, "Post-processing of the FactoryBean‘s object failed", var7); 37 } 38 } 39 40 return object; 41 } 42 }
到此, 我们终于看到了 FactoryBean 中的 getObject() 方法的调用, 回想流程, 其实只是一步步调用方法, 最终调用 getObject() 方法而已。
我们注意到在 doGetObjectFromFactoryBean() 方法中, 在 return object; 之前调用了后处理器的逻辑,其实现如下:
1 protected Object postProcessObjectFromFactoryBean(Object object, String beanName) { 2 return this.applyBeanPostProcessorsAfterInitialization(object, beanName); 3 }
1 public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { 2 Object result = existingBean; 3 Iterator var4 = this.getBeanPostProcessors().iterator(); 4 5 do { 6 if(!var4.hasNext()) { 7 return result; 8 } 9 //第一步: 遍历所有的 BeanPostProcessor 并 调用对应的方法 10 BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next(); 11 result = beanProcessor.postProcessAfterInitialization(result, beanName); 12 } while(result != null); 13 14 return result; 15 }
可能会有点晕, 但是残酷地告诉你, 之前所看到的东西, 只是我们在最开始的 doGetBean() 方法中,
if(sharedInstance != null && args == null)
这个判断从缓存中获取到的实例存在的情况, 接下来我们要看的是, 在缓存中获取不到, Spring 重新创建 Bean 的过程。
注意, 此处是 getSingleton() 方法的重载, 纠结的话看一下对应的参数吧, 反正我知道!!!o( ̄▽ ̄)d
1 public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { 2 3 Map var3 = this.singletonObjects; 4 synchronized(this.singletonObjects) { 5 //第一步: 检查是否已经创建过 6 Object singletonObject = this.singletonObjects.get(beanName); 7 if(singletonObject == null) { 8 if(this.singletonsCurrentlyInDestruction) { 9 throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while the singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)"); 10 } 11 12 if(this.logger.isDebugEnabled()) { 13 this.logger.debug("Creating shared instance of singleton bean ‘" + beanName + "‘"); 14 } 15 //第二步: 记录 bean 正在加载的状态 16 this.beforeSingletonCreation(beanName); 17 boolean recordSuppressedExceptions = this.suppressedExceptions == null; 18 if(recordSuppressedExceptions) { 19 this.suppressedExceptions = new LinkedHashSet(); 20 } 21 22 try { 23 //第三步: 初始化 bean 24 singletonObject = singletonFactory.getObject(); 25 } catch (BeanCreationException var14) { 26 BeanCreationException ex = var14; 27 if(recordSuppressedExceptions) { 28 Iterator var7 = this.suppressedExceptions.iterator(); 29 30 while(var7.hasNext()) { 31 Exception suppressedException = (Exception)var7.next(); 32 ex.addRelatedCause(suppressedException); 33 } 34 } 35 36 throw ex; 37 } finally { 38 if(recordSuppressedExceptions) { 39 this.suppressedExceptions = null; 40 } 41 //第四步: 完成加载后 清除 bean 正在加载的状态 42 this.afterSingletonCreation(beanName); 43 } 44 //第五步: 缓存加入已加载的 bean 45 this.addSingleton(beanName, singletonObject); 46 } 47 48 return singletonObject != NULL_OBJECT?singletonObject:null; 49 } 50 }
先来简单瞄下 getSingleton() 方法中, 第二步和第四步修改加载状态的方法:
1 protected void beforeSingletonCreation(String beanName) { 2 if(!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) { 3 throw new BeanCurrentlyInCreationException(beanName); 4 } 5 }
1 protected void afterSingletonCreation(String beanName) { 2 if(!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) { 3 throw new IllegalStateException("Singleton ‘" + beanName + "‘ isn‘t currently in creation"); 4 } 5 }
再看看在 getSingleton() 方法中, 第五步加入缓存中的实现逻辑:
1 protected void addSingleton(String beanName, Object singletonObject) { 2 Map var3 = this.singletonObjects; 3 //第一步: 对之前介绍过的四个集合的操作 4 synchronized(this.singletonObjects) { 5 this.singletonObjects.put(beanName, singletonObject != null?singletonObject:NULL_OBJECT); 6 this.singletonFactories.remove(beanName); 7 this.earlySingletonObjects.remove(beanName); 8 this.registeredSingletons.add(beanName); 9 } 10 }
到此, 我们已经。。。。 然而并没有做了什么, 在我们调用 FactoryBean 的 getObject() 方法的时候, 实现的逻辑其实是在 createBean() 方法中, 无论是重新创建 还是 缓存获取, 都由 createBean() 方法来:
1 protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException { 2 //第一步: 解析 Class 3 this.resolveBeanClass(mbd, beanName, new Class[0]); 4 5 try { 6 //第二步: 对 MethodOverride 属性的处理 7 mbd.prepareMethodOverrides(); 8 } catch (BeanDefinitionValidationException var5) { 9 throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "Validation of method overrides failed", var5); 10 } 11 12 Object beanInstance; 13 try { 14 //第三步: 给 BeanPostProcessors 返回代理实例 注意到 下面的一句 if(beanInstance != null) return beanInstance; 直接返回了 15 beanInstance = this.resolveBeforeInstantiation(beanName, mbd); 16 if(beanInstance != null) { 17 return beanInstance; 18 } 19 } catch (Throwable var6) { 20 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", var6); 21 } 22 //第四步: 真正创建 Bean 的逻辑 23 beanInstance = this.doCreateBean(beanName, mbd, args); 24 if(this.logger.isDebugEnabled()) { 25 this.logger.debug("Finished creating instance of bean ‘" + beanName + "‘"); 26 } 27 28 return beanInstance; 29 }
进入 prepareMethodOverrides() 方法中:
1 public void prepareMethodOverrides() throws BeanDefinitionValidationException { 2 //第一步: 遍历所有的 MethodOverrides 3 MethodOverrides methodOverrides = this.getMethodOverrides(); 4 if(!methodOverrides.isEmpty()) { 5 Iterator var2 = methodOverrides.getOverrides().iterator(); 6 7 while(var2.hasNext()) { 8 MethodOverride mo = (MethodOverride)var2.next(); 9 //第二步: 处理 replaced-method 和 lookup-method 方法 10 this.prepareMethodOverride(mo); 11 } 12 } 13 14 }
1 protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException { 2 int count = ClassUtils.getMethodCountForName(this.getBeanClass(), mo.getMethodName()); 3 if(count == 0) { 4 throw new BeanDefinitionValidationException("Invalid method override: no method with name ‘" + mo.getMethodName() + "‘ on class [" + this.getBeanClassName() + "]"); 5 } else { 6 if(count == 1) { 7 //第一步: 标记 MethodOverrides 是否覆盖 8 mo.setOverloaded(false); 9 } 10 11 } 12 }
在 createBean() 方法中, 存在一个跟重要的逻辑, 就是前置处理器的处理, 若处理器的返回值不为空, 则直接返回处理器处理后返回的 Bean, 实现的逻辑:
1 protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { 2 Object bean = null; 3 if(!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { 4 if(mbd.hasBeanClass() && !mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) { 5 //第一步: 调用处理器处理 6 bean = this.applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName); 7 if(bean != null) { 8 //第二步: 调用后处理器 9 bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName); 10 } 11 } 12 13 mbd.beforeInstantiationResolved = Boolean.valueOf(bean != null); 14 } 15 16 return bean; 17 }
在 resolveBeforeInstantiation() 方法中, 第二步调用处理器处理的方法 applyBeanPostProcessorsBeforeInstantiation() 的实现逻辑:
1 protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { 2 Iterator var3 = this.getBeanPostProcessors().iterator(); 3 //第一步: 遍历所有的 BeanPostProcessor 并调用方法 4 while(var3.hasNext()) { 5 BeanPostProcessor bp = (BeanPostProcessor)var3.next(); 6 if(bp instanceof InstantiationAwareBeanPostProcessor) { 7 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp; 8 Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); 9 if(result != null) { 10 return result; 11 } 12 } 13 } 14 15 return null; 16 }
1 public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { 2 Object result = existingBean; 3 Iterator var4 = this.getBeanPostProcessors().iterator(); 4 5 //第一步: 遍历所有的 BeanPostProcessor 并调用方法 6 do { 7 if(!var4.hasNext()) { 8 return result; 9 } 10 11 BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next(); 12 result = beanProcessor.postProcessAfterInitialization(result, beanName); 13 } while(result != null); 14 15 return result; 16 }
在 createBean() 方法中, 在梳理完 Spring 创建 bean 所有的准备工作之后, 进入 doCreateBean() 方法中, 实现真正创建 bean 的逻辑:
1 protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, Object[] args) { 2 BeanWrapper instanceWrapper = null; 3 if(mbd.isSingleton()) { 4 instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName); 5 } 6 7 if(instanceWrapper == null) { 8 //第一个: 这个方法就厉害了, 使用工厂方法 或 构造函数注入 或 简单初始化的方式创建实例 9 instanceWrapper = this.createBeanInstance(beanName, mbd, args); 10 } 11 12 final Object bean = instanceWrapper != null?instanceWrapper.getWrappedInstance():null; 13 Class<?> beanType = instanceWrapper != null?instanceWrapper.getWrappedClass():null; 14 Object var7 = mbd.postProcessingLock; 15 //第二步: MergedBeanDefinitionPostProcessor 处理器的应用 16 synchronized(mbd.postProcessingLock) { 17 if(!mbd.postProcessed) { 18 this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 19 mbd.postProcessed = true; 20 } 21 } 22 23 //第三步: 提早曝光的条件: 是单例 & 循序循环依赖 & bean 正在创建 24 boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName); 25 if(earlySingletonExposure) { 26 if(this.logger.isDebugEnabled()) { 27 this.logger.debug("Eagerly caching bean ‘" + beanName + "‘ to allow for resolving potential circular references"); 28 } 29 //第四步: 处理循环依赖的情况, 把创建实例的 ObjectFactory 加入工厂 30 this.addSingletonFactory(beanName, new ObjectFactory<Object>() { 31 public Object getObject() throws BeansException { 32 //第五步: 听说这里是 AOP 的实现的切入点, 然而我并不知道 ... 33 return AbstractAutowireCapableBeanFactory.this.getEarlyBeanReference(beanName, mbd, bean); 34 } 35 }); 36 } 37 38 Object exposedObject = bean; 39 40 try { 41 //第六步: 对 bean 属性的填充 42 this.populateBean(beanName, mbd, instanceWrapper); 43 if(exposedObject != null) { 44 //第七步: 调用初始化的方法 45 exposedObject = this.initializeBean(beanName, exposedObject, mbd); 46 } 47 } catch (Throwable var17) { 48 if(var17 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var17).getBeanName())) { 49 throw (BeanCreationException)var17; 50 } 51 52 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var17); 53 } 54 55 if(earlySingletonExposure) { 56 Object earlySingletonReference = this.getSingleton(beanName, false); 57 //第八步: 检测到循环依赖 58 if(earlySingletonReference != null) { 59 //第九步: exposedObject 么有在初始化时被改变 60 if(exposedObject == bean) { 61 exposedObject = earlySingletonReference; 62 } else if(!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) { 63 String[] dependentBeans = this.getDependentBeans(beanName); 64 Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length); 65 String[] var12 = dependentBeans; 66 int var13 = dependentBeans.length; 67 68 for(int var14 = 0; var14 < var13; ++var14) { 69 String dependentBean = var12[var14]; 70 //第十步: 检测依赖 71 if(!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { 72 actualDependentBeans.add(dependentBean); 73 } 74 } 75 //第十一步: bean 创建后 其所依赖的 bean 还没有被创建,则抛异常 76 if(!actualDependentBeans.isEmpty()) { 77 throw new BeanCurrentlyInCreationException(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 " + "‘getBeanNamesOfType‘ with the ‘allowEagerInit‘ flag turned off, for example."); 78 } 79 } 80 } 81 } 82 83 try { 84 //第十二步: 注册的 DisposableBean 85 this.registerDisposableBeanIfNecessary(beanName, bean, mbd); 86 return exposedObject; 87 } catch (BeanDefinitionValidationException var16) { 88 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16); 89 } 90 }
又是一大堆的代码, 好长好长。。。。 接着往下看
在 doCreateBean() 方法中, 第一步调用的 createBeanInstance() 方法的实现逻辑: (独白:我对代码如初恋, 代码虐我千万遍。。。 哦, 我没初恋)
1 protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { 2 //第一步: 解析 class 属性 3 Class<?> beanClass = this.resolveBeanClass(mbd, beanName, new Class[0]); 4 if(beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { 5 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn‘t public, and non-public access not allowed: " + beanClass.getName()); 6 } else if(mbd.getFactoryMethodName() != null) { 7 //第二步: 使用工厂方法初始化 8 return this.instantiateUsingFactoryMethod(beanName, mbd, args); 9 } else { 10 boolean resolved = false; 11 boolean autowireNecessary = false; 12 if(args == null) { 13 Object var7 = mbd.constructorArgumentLock; 14 synchronized(mbd.constructorArgumentLock) { 15 //第三步: 存在多个构造函数, 根据参数确定构造函数 16 if(mbd.resolvedConstructorOrFactoryMethod != null) { 17 resolved = true; 18 autowireNecessary = mbd.constructorArgumentsResolved; //构造函数的缓存属性 19 } 20 } 21 } 22 23 if(resolved) { 24 //第四步: 构造函数自动注入 或者 使用默认构造函数 25 return autowireNecessary?this.autowireConstructor(beanName, mbd, (Constructor[])null, (Object[])null):this.instantiateBean(beanName, mbd); 26 } else { 27 //第五步: 根据参数解析构造函数 28 29 Constructor<?>[] ctors = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName); 30 return ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args)?this.instantiateBean(beanName, mbd):this.autowireConstructor(beanName, mbd, ctors, args); 31 } 32 } 33 }
在 createBeanInstance() 方法中, 封装了许多方法实现逻辑, 首先来看看带参数构造函数的实例化方法 autowireConstructor() 方法的实现逻辑:
1 protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, Constructor<?>[] ctors, Object[] explicitArgs) { 2 //第一步: 继续往下调用方法 3 return (new ConstructorResolver(this)).autowireConstructor(beanName, mbd, ctors, explicitArgs); 4 }
1 public BeanWrapper autowireConstructor(final String beanName, final RootBeanDefinition mbd, Constructor<?>[] chosenCtors, Object[] explicitArgs) { 2 BeanWrapperImpl bw = new BeanWrapperImpl(); 3 this.beanFactory.initBeanWrapper(bw); 4 final Constructor<?> constructorToUse = null; 5 ConstructorResolver.ArgumentsHolder argsHolderToUse = null; 6 final Object[] argsToUse = null; 7 //第一步: 获取使用的构造函数的参数 8 if(explicitArgs != null) { 9 argsToUse = explicitArgs; 10 } else { 11 //第二步: 缓存中没有, 则从配置文件中解析 12 Object[] argsToResolve = null; 13 Object var10 = mbd.constructorArgumentLock; 14 synchronized(mbd.constructorArgumentLock) { 15 //第三步: 从缓存中获取构造函数参数 16 constructorToUse = (Constructor)mbd.resolvedConstructorOrFactoryMethod; 17 if(constructorToUse != null && mbd.constructorArgumentsResolved) { 18 argsToUse = mbd.resolvedConstructorArguments; 19 if(argsToUse == null) { 20 argsToResolve = mbd.preparedConstructorArguments; 21 } 22 } 23 } 24 //第四步: 解析构造函数的参数类型, 例如把 String 转换成 int 25 if(argsToResolve != null) { 26 argsToUse = this.resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve); 27 } 28 } 29 //第五步: 构造函数参数没有被缓存的情况, 需要解析参数 30 if(constructorToUse == null) { 31 boolean autowiring = chosenCtors != null || mbd.getResolvedAutowireMode() == 3; 32 ConstructorArgumentValues resolvedValues = null; 33 int minNrOfArgs; 34 if(explicitArgs != null) { 35 minNrOfArgs = explicitArgs.length; 36 } else { 37 //第六步: 提取配置文件中配置的构造函数的参数 38 ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues(); 39 //第七步: 封装构造函数参数的类型 40 resolvedValues = new ConstructorArgumentValues(); 41 //第八步: 构造函数参数的个数 42 minNrOfArgs = this.resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues); 43 } 44 45 Constructor<?>[] candidates = chosenCtors; 46 if(chosenCtors == null) { 47 Class beanClass = mbd.getBeanClass(); 48 49 try { 50 candidates = mbd.isNonPublicAccessAllowed()?beanClass.getDeclaredConstructors():beanClass.getConstructors(); 51 } catch (Throwable var24) { 52 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", var24); 53 } 54 } 55 //第九步: 排序给定的构造函数 56 AutowireUtils.sortConstructors(candidates); 57 int minTypeDiffWeight = 2147483647; 58 Set<Constructor<?>> ambiguousConstructors = null; 59 List<Exception> causes = null; 60 //第十步: 遍历所有的构造函数, 选取需要的构造函数 61 for(int i = 0; i < candidates.length; ++i) { 62 Constructor<?> candidate = candidates[i]; 63 Class<?>[] paramTypes = candidate.getParameterTypes(); 64 if(constructorToUse != null && argsToUse.length > paramTypes.length) { 65 break; 66 } 67 68 if(paramTypes.length >= minNrOfArgs) { 69 ConstructorResolver.ArgumentsHolder argsHolder; 70 if(resolvedValues != null) { 71 try { 72 //第十一步: 根据值构造对应参数类型的参数 73 String[] paramNames = null; 74 if(constructorPropertiesAnnotationAvailable) { 75 //第十二步: 通过注释获取参数名称 76 paramNames = ConstructorResolver.ConstructorPropertiesChecker.evaluateAnnotation(candidate, paramTypes.length); 77 } 78 79 if(paramNames == null) { 80 //第十三步: 类似工具类, 获取参数名称探索器 81 ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer(); 82 if(pnd != null) { 83 //第十四步: 获取指定构造函数的参数名称 84 paramNames = pnd.getParameterNames(candidate); 85 } 86 } 87 //第十五步: 封装构造函数参数的类 88 argsHolder = this.createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames, candidate, autowiring); 89 } catch (UnsatisfiedDependencyException var25) { 90 if(this.beanFactory.logger.isTraceEnabled()) { 91 this.beanFactory.logger.trace("Ignoring constructor [" + candidate + "] of bean ‘" + beanName + "‘: " + var25); 92 } 93 94 if(i == candidates.length - 1 && constructorToUse == null) { 95 if(causes != null) { 96 Iterator var21 = causes.iterator(); 97 98 while(var21.hasNext()) { 99 Exception cause = (Exception)var21.next(); 100 this.beanFactory.onSuppressedException(cause); 101 } 102 } 103 104 throw var25; 105 } 106 107 if(causes == null) { 108 causes = new LinkedList(); 109 } 110 111 causes.add(var25); 112 continue; 113 } 114 } else { 115 if(paramTypes.length != explicitArgs.length) { 116 continue; 117 } 118 //第十六步: 构造函数没有参数的情况 119 argsHolder = new ConstructorResolver.ArgumentsHolder(explicitArgs); 120 } 121 //第十七步: 处理构造函数参数存在父子关系的情况 122 123 int typeDiffWeight = mbd.isLenientConstructorResolution()?argsHolder.getTypeDifferenceWeight(paramTypes):argsHolder.getAssignabilityWeight(paramTypes); 124 //第十八步: 选择构造函数 125 if(typeDiffWeight < minTypeDiffWeight) { 126 constructorToUse = candidate; 127 argsHolderToUse = argsHolder; 128 argsToUse = argsHolder.arguments; 129 minTypeDiffWeight = typeDiffWeight; 130 ambiguousConstructors = null; 131 } else if(constructorToUse != null && typeDiffWeight == minTypeDiffWeight) { 132 if(ambiguousConstructors == null) { 133 ambiguousConstructors = new LinkedHashSet(); 134 ambiguousConstructors.add(constructorToUse); 135 } 136 137 ambiguousConstructors.add(candidate); 138 } 139 } 140 } 141 142 if(constructorToUse == null) { 143 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)"); 144 } 145 146 if(ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) { 147 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Ambiguous constructor matches found in bean ‘" + beanName + "‘ " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousConstructors); 148 } 149 //第十九步: 解析的构造函数加入缓存 150 if(explicitArgs == null) { 151 argsHolderToUse.storeCache(mbd, constructorToUse); 152 } 153 } 154 155 try { 156 Object beanInstance; 157 if(System.getSecurityManager() != null) { 158 beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { 159 public Object run() { 160 return ConstructorResolver.this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, ConstructorResolver.this.beanFactory, constructorToUse, argsToUse); 161 } 162 }, this.beanFactory.getAccessControlContext()); 163 } else { 164 beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse); 165 } 166 //第二十步: 构建的实例加入 BeanWrapper 中 167 bw.setWrappedInstance(beanInstance); 168 return bw; 169 } catch (Throwable var23) { 170 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", var23); 171 } 172 }
到目前为止,遇到的最恐怖的方法了, 代码量大,而且理解起来又有困难, 代码并没有删减, 看不懂就多看几遍吧。
在 createBeanInstance() 方法中, 相比有参数的构造函数的解析方法, 不带参数的构造函数的方法 instantiateBean() 要简单得多,你也可以比较一下, 其实带参数复杂的地方就是加了许多
对参数解析的逻辑,而我们真正要做的其实就是找到一个构造函数,然后初始化 Bean。
1 protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) { 2 try { 3 Object beanInstance; 4 if(System.getSecurityManager() != null) { 5 beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { 6 public Object run() { 7 return AbstractAutowireCapableBeanFactory.this.getInstantiationStrategy().instantiate(mbd, beanName, AbstractAutowireCapableBeanFactory.this); 8 } 9 }, this.getAccessControlContext()); 10 } else { 11 //第一步: 调用实例化策略进行实例化 12 beanInstance = this.getInstantiationStrategy().instantiate(mbd, beanName, this); 13 } 14 15 BeanWrapper bw = new BeanWrapperImpl(beanInstance); 16 this.initBeanWrapper(bw); 17 return bw; 18 } catch (Throwable var6) { 19 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", var6); 20 } 21 }
看看调用实例化策略实例化是调用的 instantiate() 方法:
1 public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { 2 //第一步: 实例化的过程, 需要判断是否需要重写方法, 若有则需要使用 CGLib 进行代理 3 if(beanDefinition.getMethodOverrides().isEmpty()) { 4 Object var5 = beanDefinition.constructorArgumentLock; 5 Constructor constructorToUse; 6 synchronized(beanDefinition.constructorArgumentLock) { 7 constructorToUse = (Constructor)beanDefinition.resolvedConstructorOrFactoryMethod; 8 if(constructorToUse == null) { 9 final Class<?> clazz = beanDefinition.getBeanClass(); 10 if(clazz.isInterface()) { 11 throw new BeanInstantiationException(clazz, "Specified class is an interface"); 12 } 13 14 try { 15 if(System.getSecurityManager() != null) { 16 constructorToUse = (Constructor)AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() { 17 public Constructor<?> run() throws Exception { 18 return clazz.getDeclaredConstructor((Class[])null); 19 } 20 }); 21 } else { 22 constructorToUse = clazz.getDeclaredConstructor((Class[])null); 23 } 24 25 beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse; 26 } catch (Exception var9) { 27 throw new BeanInstantiationException(clazz, "No default constructor found", var9); 28 } 29 } 30 } 31 32 return BeanUtils.instantiateClass(constructorToUse, new Object[0]); 33 } else { 34 return this.instantiateWithMethodInjection(beanDefinition, beanName, owner); 35 } 36 }
稍微瞄一下 CGLib 的 instantiate() 方法, 装个逼就跑:
1 public Object instantiate(Constructor<?> ctor, Object[] args) { 2 Enhancer enhancer = new Enhancer(); 3 enhancer.setSuperclass(this.beanDefinition.getBeanClass()); 4 enhancer.setCallbackFilter(new CglibSubclassingInstantiationStrategy.CglibSubclassCreator.CallbackFilterImpl()); 5 enhancer.setCallbacks(new Callback[]{NoOp.INSTANCE, new CglibSubclassingInstantiationStrategy.CglibSubclassCreator.LookupOverrideMethodInterceptor(), new CglibSubclassingInstantiationStrategy.CglibSubclassCreator.ReplaceOverrideMethodInterceptor()}); 6 return ctor == null?enhancer.create():enhancer.create(ctor.getParameterTypes(), args); 7 }
在 doCreateBean() 方法中, 为了解决循环依赖的问题,提前曝光 bean 的 ObjectFactory 的 addSingletonFactory() 中, 对 Bean 调用 PostProcessor
处理的方法 getEarlyBeanReference() 方法的实现逻辑:
1 protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) { 2 Object exposedObject = bean; 3 if(bean != null && !mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) { 4 Iterator var5 = this.getBeanPostProcessors().iterator(); 5 6 while(var5.hasNext()) { 7 BeanPostProcessor bp = (BeanPostProcessor)var5.next(); 8 if(bp instanceof SmartInstantiationAwareBeanPostProcessor) { 9 //第一步: 主要是调用 SmartInstantiationAwareBeanPostProcessor 处理 Bean 10 SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor)bp; 11 exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); 12 if(exposedObject == null) { 13 return exposedObject; 14 } 15 } 16 } 17 } 18 19 return exposedObject; 20 }
在 doCreateBean() 方法中, 第六步对 Bean 属性的填充 populateBean() 方法的实现的逻辑:
1 protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) { 2 //第一步: 获取要填充的属性集合 3 PropertyValues pvs = mbd.getPropertyValues(); 4 if(bw == null) { 5 if(!((PropertyValues)pvs).isEmpty()) { 6 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); 7 } 8 } else { 9 boolean continueWithPropertyPopulation = true; 10 //第二步: 使用 InstantiationAwareBeanPostProcessors 修改 Bean 11 if(!mbd.isSynthetic() && 12 this.hasInstantiationAwareBeanPostProcessors()) { 13 Iterator var6 = this.getBeanPostProcessors().iterator(); 14 15 while(var6.hasNext()) { 16 BeanPostProcessor bp = (BeanPostProcessor)var6.next(); 17 if(bp instanceof InstantiationAwareBeanPostProcessor) { 18 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp; 19 //第三步: 根据 InstantiationAwareBeanPostProcessors 的返回值判断是否继续填充 Bean 20 if(!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { 21 continueWithPropertyPopulation = false; 22 break; 23 } 24 } 25 } 26 } 27 28 if(continueWithPropertyPopulation) { 29 if(mbd.getResolvedAutowireMode() == 1 || mbd.getResolvedAutowireMode() == 2) { 30 MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs); 31 if(mbd.getResolvedAutowireMode() == 1) { 32 //第四步: 根据名称自动注入 33 this.autowireByName(beanName, mbd, bw, newPvs); 34 } 35 36 if(mbd.getResolvedAutowireMode() == 2) { 37 //第五步: 根据类型自动注入 38 this.autowireByType(beanName, mbd, bw, newPvs); 39 } 40 41 pvs = newPvs; 42 } 43 //第六步: 后处理器的调用 44 boolean hasInstAwareBpps = this.hasInstantiationAwareBeanPostProcessors(); 45 //第七步: 检查依赖 46 boolean needsDepCheck = mbd.getDependencyCheck() != 0; 47 if(hasInstAwareBpps || needsDepCheck) { 48 PropertyDescriptor[] filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); 49 if(hasInstAwareBpps) { 50 Iterator var9 = this.getBeanPostProcessors().iterator(); 51 52 while(var9.hasNext()) { 53 BeanPostProcessor bp = (BeanPostProcessor)var9.next(); 54 if(bp instanceof InstantiationAwareBeanPostProcessor) { 55 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp; 56 //第八步: 对所有需要依赖的属性进行后处理 57 pvs = ibp.postProcessPropertyValues((PropertyValues)pvs, filteredPds, bw.getWrappedInstance(), beanName); 58 if(pvs == null) { 59 return; 60 } 61 } 62 } 63 } 64 65 if(needsDepCheck) { 66 //第十步: 依赖检查, 对应的是 depends-on 属性 67 this.checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs); 68 } 69 } 70 //第十一步: 把属性封装到 bean 中 71 this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs); 72 } 73 } 74 }
在 populateBean() 方法中,第四步 autowireByName() 方法的实现逻辑:
1 protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { 2 //第一步: 获取 BeanWrapper 中需要依赖注入的属性 3 String[] propertyNames = this.unsatisfiedNonSimpleProperties(mbd, bw); 4 String[] var6 = propertyNames; 5 int var7 = propertyNames.length; 6 7 for(int var8 = 0; var8 < var7; ++var8) { 8 String propertyName = var6[var8]; 9 if(this.containsBean(propertyName)) { 10 //第二步: 递归初始化相关的 bean 并再加入到 pvs 中 11 Object bean = this.getBean(propertyName); 12 pvs.add(propertyName, bean); 13 //第三步: 注册依赖 14 this.registerDependentBean(propertyName, beanName); 15 if(this.logger.isDebugEnabled()) { 16 this.logger.debug("Added autowiring by name from bean name ‘" + beanName + "‘ via property ‘" + propertyName + "‘ to bean named ‘" + propertyName + "‘"); 17 } 18 } else if(this.logger.isTraceEnabled()) { 19 this.logger.trace("Not autowiring property ‘" + propertyName + "‘ of bean ‘" + beanName + "‘ by name: no matching bean found"); 20 } 21 } 22 23 }
在 populateBean() 方法中,第五步 autowireByType() 方法的实现逻辑:
1 protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { 2 TypeConverter converter = this.getCustomTypeConverter(); 3 if(converter == null) { 4 converter = bw; 5 } 6 7 Set<String> autowiredBeanNames = new LinkedHashSet(4); 8 //第一步: 寻找 BeanWrapper 中需要注入的属性 9 String[] propertyNames = this.unsatisfiedNonSimpleProperties(mbd, bw); 10 String[] var8 = propertyNames; 11 int var9 = propertyNames.length; 12 13 for(int var10 = 0; var10 < var9; ++var10) { 14 String propertyName = var8[var10]; 15 16 try { 17 PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); 18 //第二步: 忽略装载 Object 类型 19 if(!Object.class.equals(pd.getPropertyType())) { 20 MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); 21 boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass()); 22 DependencyDescriptor desc = new AbstractAutowireCapableBeanFactory.AutowireByTypeDependencyDescriptor(methodParam, eager); 23 //第三步: 解析指定 Bean 的 属性 所 匹配的值, 并加入 autowiredBeanNames 中 24 Object autowiredArgument = this.resolveDependency(desc, beanName, autowiredBeanNames, (TypeConverter)converter); 25 if(autowiredArgument != null) { 26 pvs.add(propertyName, autowiredArgument); 27 } 28 29 Iterator var17 = autowiredBeanNames.iterator(); 30 31 while(var17.hasNext()) { 32 String autowiredBeanName = (String)var17.next(); 33 //第四步: 注册依赖 34 this.registerDependentBean(autowiredBeanName, beanName); 35 if(this.logger.isDebugEnabled()) { 36 this.logger.debug("Autowiring by type from bean name ‘" + beanName + "‘ via property ‘" + propertyName + "‘ to bean named ‘" + autowiredBeanName + "‘"); 37 } 38 } 39 40 autowiredBeanNames.clear(); 41 } 42 } catch (BeansException var19) { 43 throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, var19); 44 } 45 } 46 47 }
在 autowireByType() 方法中, 第三步中寻找类型匹配的方法 resolveDependency() 的实现逻辑:
1 public Object resolveDependency(DependencyDescriptor descriptor, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException { 2 descriptor.initParameterNameDiscovery(this.getParameterNameDiscoverer()); 3 if(descriptor.getDependencyType().equals(ObjectFactory.class)) { 4 //第一步: 处理 ObjectFactory 类型的情况 5 return new DefaultListableBeanFactory.DependencyObjectFactory(descriptor, beanName); 6 } else 7 //第二步: 处理 javaxInjectProviderClass 类型注入的情况 8 if(descriptor.getDependencyType().equals(javaxInjectProviderClass)) { 9 return (new DefaultListableBeanFactory.DependencyProviderFactory(null)).createDependencyProvider(descriptor, beanName); 10 } else { 11 Object result = this.getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(descriptor, beanName); 12 if(result == null) { 13 //第三步: 通用处理逻辑 14 result = this.doResolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter); 15 } 16 17 return result; 18 } 19 }
1 public Object doResolveDependency(DependencyDescriptor descriptor, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException { 2 Class<?> type = descriptor.getDependencyType(); 3 Object value = this.getAutowireCandidateResolver().getSuggestedValue(descriptor); 4 if(value == null) { 5 Object result; 6 Class keyType; 7 DependencyDescriptor targetDesc; 8 Map matchingBeans; 9 TypeConverter converter; 10 //第一步: 属性是数组类型 11 if(type.isArray()) { 12 keyType = type.getComponentType(); 13 targetDesc = new DependencyDescriptor(descriptor); 14 targetDesc.increaseNestingLevel(); 15 matchingBeans = this.findAutowireCandidates(beanName, keyType, targetDesc); 16 if(matchingBeans.isEmpty()) { 17 if(descriptor.isRequired()) { 18 this.raiseNoSuchBeanDefinitionException(keyType, "array of " + keyType.getName(), descriptor); 19 } 20 21 return null; 22 } else { 23 if(autowiredBeanNames != null) { 24 autowiredBeanNames.addAll(matchingBeans.keySet()); 25 } 26 27 converter = typeConverter != null?typeConverter:this.getTypeConverter(); 28 result = converter.convertIfNecessary(matchingBeans.values(), type); 29 if(this.dependencyComparator != null && result instanceof Object[]) { 30 Arrays.sort((Object[])((Object[])result), this.dependencyComparator); 31 } 32 33 return result; 34 } 35 } else if(Collection.class.isAssignableFrom(type) && type.isInterface()) { 36 //第二步: 属性是 Collection 类型 37 keyType = descriptor.getCollectionType(); 38 if(keyType == null) { 39 if(descriptor.isRequired()) { 40 throw new FatalBeanException("No element type declared for collection [" + type.getName() + "]"); 41 } else { 42 return null; 43 } 44 } else { 45 targetDesc = new DependencyDescriptor(descriptor); 46 targetDesc.increaseNestingLevel(); 47 matchingBeans = this.findAutowireCandidates(beanName, keyType, targetDesc); 48 if(matchingBeans.isEmpty()) { 49 if(descriptor.isRequired()) { 50 this.raiseNoSuchBeanDefinitionException(keyType, "collection of " + keyType.getName(), descriptor); 51 } 52 53 return null; 54 } else { 55 if(autowiredBeanNames != null) { 56 autowiredBeanNames.addAll(matchingBeans.keySet()); 57 } 58 59 converter = typeConverter != null?typeConverter:this.getTypeConverter(); 60 result = converter.convertIfNecessary(matchingBeans.values(), type); 61 if(this.dependencyComparator != null && result instanceof List) { 62 Collections.sort((List)result, this.dependencyComparator); 63 } 64 65 return result; 66 } 67 } 68 } else if(Map.class.isAssignableFrom(type) && type.isInterface()) { 69 //第三步: 属性是 Map 类型 70 keyType = descriptor.getMapKeyType(); 71 if(keyType != null && String.class.isAssignableFrom(keyType)) { 72 Class<?> valueType = descriptor.getMapValueType(); 73 if(valueType == null) { 74 if(descriptor.isRequired()) { 75 throw new FatalBeanException("No value type declared for map [" + type.getName() + "]"); 76 } else { 77 return null; 78 } 79 } else { 80 DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor); 81 targetDesc.increaseNestingLevel(); 82 Map<String, Object> matchingBeans = this.findAutowireCandidates(beanName, valueType, targetDesc); 83 if(matchingBeans.isEmpty()) { 84 if(descriptor.isRequired()) { 85 this.raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor); 86 } 87 88 return null; 89 } else { 90 if(autowiredBeanNames != null) { 91 autowiredBeanNames.addAll(matchingBeans.keySet()); 92 } 93 94 return matchingBeans; 95 } 96 } 97 } else if(descriptor.isRequired()) { 98 throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() + "] must be assignable to [java.lang.String]"); 99 } else { 100 return null; 101 } 102 } else { 103 Map<String, Object> matchingBeans = this.findAutowireCandidates(beanName, type, descriptor); 104 if(matchingBeans.isEmpty()) { 105 if(descriptor.isRequired()) { 106 this.raiseNoSuchBeanDefinitionException(type, "", descriptor); 107 } 108 109 return null; 110 } else if(matchingBeans.size() > 1) { 111 String primaryBeanName = this.determinePrimaryCandidate(matchingBeans, descriptor); 112 if(primaryBeanName == null) { 113 throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet()); 114 } else { 115 if(autowiredBeanNames != null) { 116 autowiredBeanNames.add(primaryBeanName); 117 } 118 119 return matchingBeans.get(primaryBeanName); 120 } 121 } else { 122 Entry<String, Object> entry = (Entry)matchingBeans.entrySet().iterator().next(); 123 if(autowiredBeanNames != null) { 124 autowiredBeanNames.add(entry.getKey()); 125 } 126 127 return entry.getValue(); 128 } 129 } 130 } else { 131 //第四步: 处理 @Value 的情况 132 if(value instanceof String) { 133 String strVal = this.resolveEmbeddedValue((String)value); 134 BeanDefinition bd = beanName != null && this.containsBean(beanName)?this.getMergedBeanDefinition(beanName):null; 135 value = this.evaluateBeanDefinitionString(strVal, bd); 136 } 137 138 TypeConverter converter = typeConverter != null?typeConverter:this.getTypeConverter(); 139 return descriptor.getField() != null?converter.convertIfNecessary(value, type, descriptor.getField()):converter.convertIfNecessary(value, type, descriptor.getMethodParameter()); 140 } 141 }
呵呵哈, 一言不合就是一百多行代码,在 doResolveDependency() 方法中,对不同类型采取不同的解析方法,总体来说。。。。我只看懂了 if 的判断。。。。
在 populateBean() 方法中, 第十一步把属性应用到 Bean 当中实现逻辑:
1 protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { 2 if(pvs != null && !pvs.isEmpty()) { 3 MutablePropertyValues mpvs = null; 4 if(System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) { 5 ((BeanWrapperImpl)bw).setSecurityContext(this.getAccessControlContext()); 6 } 7 8 List original; 9 if(pvs instanceof MutablePropertyValues) { 10 mpvs = (MutablePropertyValues)pvs; 11 //第一步: 判断如果已经转换为对应的类型, 设置到 BeanWrapper 中 12 if(mpvs.isConverted()) { 13 try { 14 bw.setPropertyValues(mpvs); 15 return; 16 } catch (BeansException var18) { 17 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", var18); 18 } 19 } 20 21 original = mpvs.getPropertyValueList(); 22 } else { 23 //第二步: 若属性不是 MutablePropertyValues 类型,则直接封装 24 original = Arrays.asList(pvs.getPropertyValues()); 25 } 26 27 TypeConverter converter = this.getCustomTypeConverter(); 28 if(converter == null) { 29 converter = bw; 30 } 31 //第三步: 获取对应的属性解析器 32 BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, (TypeConverter)converter); 33 //第四步: 放置类型转换后的属性的集合 34 List<PropertyValue> deepCopy = new ArrayList(original.size()); 35 boolean resolveNecessary = false; 36 Iterator var11 = original.iterator(); 37 38 while(true) { 39 while(var11.hasNext()) { 40 PropertyValue pv = (PropertyValue)var11.next(); 41 if(pv.isConverted()) { 42 deepCopy.add(pv); 43 } else { 44 String propertyName = pv.getName(); 45 Object originalValue = pv.getValue(); 46 //第五步: 遍历所有的属性, 转换类型 47 Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); 48 Object convertedValue = resolvedValue; 49 boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName); 50 if(convertible) { 51 convertedValue = this.convertForProperty(resolvedValue, propertyName, bw, (TypeConverter)converter); 52 } 53 54 if(resolvedValue == originalValue) { 55 if(convertible) { 56 pv.setConvertedValue(convertedValue); 57 } 58 //第六步: 往集合当中添加类型转换后的属性 59 deepCopy.add(pv); 60 } else if(convertible && originalValue instanceof TypedStringValue && !((TypedStringValue)originalValue).isDynamic() && !(convertedValue instanceof Collection) && !ObjectUtils.isArray(convertedValue)) { 61 pv.setConvertedValue(convertedValue); 62 deepCopy.add(pv); 63 } else { 64 resolveNecessary = true; 65 deepCopy.add(new PropertyValue(pv, convertedValue)); 66 } 67 } 68 } 69 70 if(mpvs != null && !resolveNecessary) { 71 mpvs.setConverted(); 72 } 73 74 try { 75 //第七步: 把转换后的属性设置回原来的 BeanWrapper 中 76 bw.setPropertyValues(new MutablePropertyValues(deepCopy)); 77 return; 78 } catch (BeansException var19) { 79 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", var19); 80 } 81 } 82 } 83 }
在 doCreateBean() 方法中, 第七步调用初始化方法 initializeBean() 的实现逻辑:
1 protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { 2 if(System.getSecurityManager() != null) { 3 AccessController.doPrivileged(new PrivilegedAction<Object>() { 4 public Object run() { 5 //第一步: 对特殊 Bean 的处理 6 AbstractAutowireCapableBeanFactory.this.invokeAwareMethods(beanName, bean); 7 return null; 8 } 9 }, this.getAccessControlContext()); 10 } else { 11 this.invokeAwareMethods(beanName, bean); 12 } 13 14 Object wrappedBean = bean; 15 if(mbd == null || !mbd.isSynthetic()) { 16 //第二步: 运用处理器 17 wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName); 18 } 19 20 try { 21 //第三步: 调用自定义的初始化方法 22 this.invokeInitMethods(beanName, wrappedBean, mbd); 23 } catch (Throwable var6) { 24 throw new BeanCreationException(mbd != null?mbd.getResourceDescription():null, beanName, "Invocation of init method failed", var6); 25 } 26 27 if(mbd == null || !mbd.isSynthetic()) { 28 //第四步: 运用处理器 29 wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); 30 } 31 32 return wrappedBean; 33 }
在 initializeBean()方法中, 第一步对特殊 bean 的处理逻辑:
1 private void invokeAwareMethods(String beanName, Object bean) { 2 if(bean instanceof Aware) { 3 if(bean instanceof BeanNameAware) { 4 ((BeanNameAware)bean).setBeanName(beanName); 5 } 6 7 if(bean instanceof BeanClassLoaderAware) { 8 ((BeanClassLoaderAware)bean).setBeanClassLoader(this.getBeanClassLoader()); 9 } 10 11 if(bean instanceof BeanFactoryAware) { 12 ((BeanFactoryAware)bean).setBeanFactory(this); 13 } 14 } 15 16 }
逻辑比较简单, 调用接口的方法。
接下来是我们已经十分熟悉的处理器应用的逻辑:
1 public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { 2 Object result = existingBean; 3 Iterator var4 = this.getBeanPostProcessors().iterator(); 4 5 do { 6 if(!var4.hasNext()) { 7 return result; 8 } 9 10 BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next(); 11 result = beanProcessor.postProcessBeforeInitialization(result, beanName); 12 } while(result != null); 13 14 return result; 15 }
1 public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { 2 Object result = existingBean; 3 Iterator var4 = this.getBeanPostProcessors().iterator(); 4 5 do { 6 if(!var4.hasNext()) { 7 return result; 8 } 9 10 BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next(); 11 result = beanProcessor.postProcessAfterInitialization(result, beanName); 12 } while(result != null); 13 14 return result; 15 }
在 initialBean() 方法中, 第三步调用自定义 invokeInitMethods() 方法的实现逻辑:
1 protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { 2 //第一步: 判断是否是 InitialingBean 3 boolean isInitializingBean = bean instanceof InitializingBean; 4 if(isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { 5 if(this.logger.isDebugEnabled()) { 6 this.logger.debug("Invoking afterPropertiesSet() on bean with name ‘" + beanName + "‘"); 7 } 8 9 if(System.getSecurityManager() != null) { 10 try { 11 AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { 12 public Object run() throws Exception { 13 //第二步: 调用 afterPropertiesSet() 方法 14 ((InitializingBean)bean).afterPropertiesSet(); 15 return null; 16 } 17 }, this.getAccessControlContext()); 18 } catch (PrivilegedActionException var6) { 19 throw var6.getException(); 20 } 21 } else { 22 ((InitializingBean)bean).afterPropertiesSet(); 23 } 24 } 25 26 if(mbd != null) { 27 String initMethodName = mbd.getInitMethodName(); 28 if(initMethodName != null && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { 29 //第三步: 调用自定义的 初始化方法 30 this.invokeCustomInitMethod(beanName, bean, mbd); 31 } 32 } 33 34 }
最终来到 doCreateBean() 方法中的第十二步, 注册 DisposableBean 的 registerDisposableBeanIfNecessary() 方法的实现逻辑:
1 protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) { 2 AccessControlContext acc = System.getSecurityManager() != null?this.getAccessControlContext():null; 3 if(!mbd.isPrototype() && this.requiresDestruction(bean, mbd)) { 4 //第一步: 对单例的处理 5 if(mbd.isSingleton()) { 6 this.registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessors(), acc)); 7 } else { 8 //第二步: 对 scope 的处理 9 Scope scope = (Scope)this.scopes.get(mbd.getScope()); 10 if(scope == null) { 11 throw new IllegalStateException("No Scope registered for scope ‘" + mbd.getScope() + "‘"); 12 } 13 14 scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessors(), acc)); 15 } 16 } 17 18 }
到此,我们梳理了一遍 Spring 加载 Bean 的逻辑, Spring 的核心 XML 文件的读取到 Bean 的加载都学习了一遍。 d=====( ̄▽ ̄*)b
好累, 没想到写这篇博客写了一天。 Bean 的加载部分里面有些内容确实自己有些不太理解的,在以后的学习过程中慢慢的补上来。今天接下来的时间要休息一下了,坐在电脑
前坐了一天,背部好痛, 看武林外传去了。 大家加油哈。哈哈哈哈哈哈哈哈哈哈O(∩_∩)O~~
以上是关于Spring源码学习笔记的主要内容,如果未能解决你的问题,请参考以下文章
初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段