当前位置 : 主页 > 编程语言 > java >

Spring5 IOC容器解析——createBean()方法分析下

来源:互联网 收集:自由互联 发布时间:2023-02-04
前言 接着Spring5IOC容器解析--createBean()方法分析上我们继续解析创建 bean 实例的剩下内容。 正文 首先,我们回到 doCreateBean 方法中,doCreateBean()方法主要是根据 beanName、mbd、args,使用对

前言

接着Spring5IOC容器解析--createBean()方法分析上我们继续解析创建 bean 实例的剩下内容。

正文

首先,我们回到 doCreateBean 方法中,doCreateBean()方法主要是根据 beanName、mbd、args,使用对应的策略创建 bean 实例,并返回包装类 BeanWrapper。

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException { // Instantiate the bean. // 1.新建Bean包装类 BeanWrapper instanceWrapper = null; //如果RootBeanDefinition是单例的,则移除未完成的FactoryBean实例的缓存 if (mbd.isSingleton()) { // 2.如果是FactoryBean,则需要先移除未完成的FactoryBean实例的缓存 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { // 3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args); } // 4.拿到创建好的Bean实例 final Object bean = instanceWrapper.getWrappedInstance(); // 5.拿到Bean实例的类型 Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { // 6.应用后置处理器MergedBeanDefinitionPostProcessor,允许修改MergedBeanDefinition, // Autowired注解、Value注解正是通过此方法实现注入类型的预解析 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. // 7.判断是否需要提早曝光实例:单例 && 允许循环依赖 && 当前bean正在创建中 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } // 8.提前曝光beanName的ObjectFactory,用于解决循环引用 // 8.1 应用后置处理器SmartInstantiationAwareBeanPostProcessor,允许返回指定bean的早期引用,若没有则直接返回bean addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. // 初始化bean实例。 Object exposedObject = bean; try { // 9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例 populateBean(beanName, mbd, instanceWrapper); // 10.对bean进行初始化 exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { // 11.如果允许提前曝光实例,则进行循环依赖检查 Object earlySingletonReference = getSingleton(beanName, false); // 11.1 earlySingletonReference只有在当前解析的bean存在循环依赖的情况下才会不为空 if (earlySingletonReference != null) { if (exposedObject == bean) { // 11.2 如果exposedObject没有在initializeBean方法中被增强,则不影响之前的循环引用 exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { // 11.3 如果exposedObject在initializeBean方法中被增强 && 不允许在循环引用的情况下使用注入原始bean实例 // && 当前bean有被其他bean依赖 // 11.4 拿到依赖当前bean的所有bean的beanName数组 String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { // 11.5 尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { // 11.6 移除失败的添加到 actualDependentBeans actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { // 11.7 如果存在移除失败的,则抛出异常,因为存在bean依赖了“脏数据” 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 " + "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. try { // 12.注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } // 13.完成创建并返回 return exposedObject; } }
  • earlySingletonReference 只有在当前解析的 bean 存在循环依赖的情况下才会不为空。

因为如果不是循环依赖,只会在完全创建完 bean 实例才会添加到 singletonObjects 缓存。此时,我们正在创建 bean 的过程中,还没有完全创建完,singletonObjects 缓存是肯定没有当前 beanName 的;而如果不存在循环引用,从 doGetBean 方法开始,getSingleton 方法只会在最初 doGetBean 方法里调用一次,不存在循环引用,也就用不到提前曝光的 ObjectFactory 来创建 bean 对象,从而 earlySingletonObjects 缓存肯定也是没有 beanName 的 bean 实例对象的,所以必然返回空。

  • 注册用于销毁的 bean,执行销毁操作的有三种:自定义 destroy 方法、DisposableBean 接口、DestructionAwareBeanPostProcessor。

applyMergedBeanDefinitionPostProcessors

  • 应用后置处理器 MergedBeanDefinitionPostProcessor,允许修改MergedBeanDefinition,Autowired注解、Value注解正是通过此方法实现注入类型的预解析。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) { // 1.获取BeanFactory中已注册的BeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof MergedBeanDefinitionPostProcessor) { // 2.调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法 MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp; //重点关注AutowiredAnnotationBeanPostProcessor,该类会把@Autowired等标记的 //需要依赖注入的成员变量或者方法实例给记录下来,方便后续populateBean使用 bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName); } } } }

addSingletonFactory

  • 提前曝光beanName的ObjectFactory,用于解决循环引用。

  • 应用后置处理器SmartInstantiationAwareBeanPostProcessor,允许返回指定bean的早期引用,若没有则直接返回bean。

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry { /** Cache of singleton objects: bean name to bean instance. */ //一级缓存:单例对象缓存池,beanName->Bean,其中存储的就是实例化,属性赋值成功之后的单例对象 private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256); /** Cache of singleton factories: bean name to ObjectFactory. */ //三级缓存:单例工厂的缓存,beanName->ObjectFactory,添加进去的时候实例还未具备属性 // 用于保存beanName和创建bean的工厂之间的关系map,单例Bean在创建之初过早的暴露出去的Factory, // 为什么采用工厂方式,是因为有些Bean是需要被代理的,总不能把代理前的暴露出去那就毫无意义了 private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16); /** Cache of early singleton objects: bean name to bean instance. */ //二级缓存:早期的单例对象,beanName->Bean,其中存储的是实例化之后,属性未赋值的单例对象 // 执行了工厂方法生产出来的Bean,bean被放进去之后, // 那么当bean在创建过程中,就可以通过getBean方法获取到 private final Map<String, Object> earlySingletonObjects = new HashMap<>(16); /** Set of registered singletons, containing the bean names in registration order. */ private final Set<String> registeredSingletons = new LinkedHashSet<>(256); protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(singletonFactory, "Singleton factory must not be null"); synchronized (this.singletonObjects) { // 1.如果beanName不存在于singletonObjects缓存中 if (!this.singletonObjects.containsKey(beanName)) { //往三级缓存里添加 // 2.将beanName和singletonFactory注册到singletonFactories缓存(beanName -> 该beanName的单例工厂) this.singletonFactories.put(beanName, singletonFactory); //清除此Bean在二级缓存里的缓存信息 // 3.移除earlySingletonObjects缓存中的beanName(beanName -> beanName的早期单例对象) this.earlySingletonObjects.remove(beanName); //这里为了记录注册单例的顺序 // 4.将beanName注册到registeredSingletons缓存(已经注册的单例集合) this.registeredSingletons.add(beanName); } } } }

在Spring5IOC容器解析--refresh()方法分析中,通过提前曝光的 ObjectFactory 获得 “不完整” 的 bean 实例,从而解决循环引用的问题,ObjectFactory 就是通过这边的 singletonFactories缓存来进行曝光的。

getEarlyBeanReference

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) { Object exposedObject = bean; // 1.如果bean不为空 && mbd不是合成 && 存在InstantiationAwareBeanPostProcessors if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { // 2.应用所有SmartInstantiationAwareBeanPostProcessor,调用getEarlyBeanReference方法 if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; // 3.允许SmartInstantiationAwareBeanPostProcessor返回指定bean的早期引用 exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); } } } // 4.返回要作为bean引用公开的对象,如果没有SmartInstantiationAwareBeanPostProcessor修改,则返回的是入参的bean对象本身 return exposedObject; } }

populateBean

  • 对 bean 进行属性填充;其中,可能存在依赖于其他 bean 的属性,则会递归初始化依赖的 bean 实例。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { // bw为空时的处理 if (bw == null) { // 如果bw为空,属性不为空,抛异常,无法将属性值应用于null实例 if (mbd.hasPropertyValues()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. // 如果bw为空,属性也为空,则跳过 return; } } // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. // 给InstantiationAwareBeanPostProcessors最后一次机会在属性注入前修改Bean的属性值,也可以控制是否继续填充Bean // 具体通过调用postProcessAfterInstantiation方法,如果调用返回false,表示不必继续进行依赖注入,直接返回 // 主要是让用户可以自定义属性注入。比如用户实现一个 InstantiationAwareBeanPostProcessor 类型的后置处理器, // 并通过 postProcessAfterInstantiation 方法向 bean 的成员变量注入自定义的信息。 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { // 如果mbd不是合成的 && 存在InstantiationAwareBeanPostProcessor,则遍历处理InstantiationAwareBeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; // 在bean实例化后,属性填充之前被调用,允许修改bean的属性,如果返回false,则跳过之后的属性填充 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } } // pvs是一个MutablePropertyValues实例,里面实现了PropertyValues接口, // 提供属性的读写操作实现,同时可以通过调用构造函数实现深拷贝 //获取BeanDefinition里面为Bean设置上的属性值 PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // 根据Bean配置的依赖注入方式完成注入,默认是0,即不走以下逻辑,所有的依赖注入都需要在xml文件中有显式的配置 // 如果设置了相关的依赖装配方式,会遍历Bean中的属性,根据类型或名称来完成相应注入,无需额外配置 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. // 根据beanName进行autowiring自动装配处理 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. //根据Bean的类型进行autowiring自动装配处理 if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } //BeanFactory是否注册过InstantiationAwareBeanPostProcessors boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); //是否进行依赖检查,默认为false boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null; //注册过InstantiationAwareBeanPostProcessors 或者 需要依赖检查 if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } // 7.1 应用后置处理器InstantiationAwareBeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //在这里会对@Autowired标记的属性进行依赖注入 //调用AutowiredAnnotationBeanPostProcessor的postProcessProperties PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } // 对解析完但未设置的属性再进行处理 pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; } } } // 依赖检查,对应depend-on属性,3.0已经弃用此属性 if (needsDepCheck) { // 过滤出所有需要进行依赖检查的属性编辑器 if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } checkDependencies(beanName, mbd, filteredPds, pvs); } if (pvs != null) { //最终将属性注入到Bean的Wrapper实例里,这里的注入主要是供 //显式配置了autowiredbyName或者ByType的属性注入, //针对注解来讲,由于在AutowiredAnnotationBeanPostProcessor已经完成了注入, //所以此处不执行 applyPropertyValues(beanName, mbd, bw, pvs); } } }

应用后置处理器 InstantiationAwareBeanPostProcessor 的方法 postProcessPropertyValues,进行属性填充前的再次处理。现在最常用的 @Autowire 属性注入就是这边注入依赖的 bean 实例对象,具体实现在 AutowiredAnnotationBeanPostProcessor的postProcessProperties方法完成注入。

 

将所有 PropertyValues 中的属性填充到 bean 中。

autowireByName

  • 解析 autowireByName 的注入
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected void autowireByName( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { //获取要注入的非简单类型的属性名称 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { // 检测是否存在与 propertyName 相关的 bean 或 BeanDefinition。 // 若存在,则调用 BeanFactory.getBean 方法获取 bean 实例 if (containsBean(propertyName)) { // 从容器中获取相应的 bean 实例 Object bean = getBean(propertyName); // 将解析出的 bean 存入到属性值列表pvs中 pvs.add(propertyName, bean); // 注册依赖关系到缓存(beanName依赖propertyName) registerDependentBean(propertyName, beanName); if (logger.isTraceEnabled()) { logger.trace("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } } }

unsatisfiedNonSimpleProperties

  • 获取要注入的非简单类型的属性名称
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { /* * 获取非简单类型属性的名称,且该属性未被配置在配置文件中。 * bean class="org.springframework.aop.framework.ProxyFactoryBean"> * <property name="target"> <ref parent="accountService"/> * </property> * </bean> * Spring 认为的"简单类型"属性有哪些,如下: * 1. CharSequence 接口的实现类,比如 String * 2. Enum * 3. Date * 4. URI/URL * 5. Number 的继承类,比如 Integer/Long * 6. byte/short/int... 等基本类型 * 7. Locale * 8. 以上所有类型的数组形式,比如 String[]、Date[]、int[] 等等 * * 除了要求非简单类型的属性外,还要求属性未在配置文件中配置过,也就是 pvs.contains(pd.getName()) = false。 */ protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) { Set<String> result = new TreeSet<>(); // 1.拿到mdb的属性值 PropertyValues pvs = mbd.getPropertyValues(); // 2.拿到bw的PropertyDescriptors PropertyDescriptor[] pds = bw.getPropertyDescriptors(); // 3.遍历bw的PropertyDescriptors for (PropertyDescriptor pd : pds) { // 4.pd用于写入属性值的方法不为空 && pd不是从依赖性检查中排除的bean属性 && pd不包含在pvs里 // && pd的属性类型不是“简单”属性(基础类型、枚举、Number等) // 4.1 isSimpleProperty: 判断属性是不是“简单”属性 if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) && !BeanUtils.isSimpleProperty(pd.getPropertyType())) { // 4.2 符合条件,则添加pd的name到result中 result.add(pd.getName()); } } return StringUtils.toStringArray(result); } }

isSimpleProperty

  • 判断属性是不是 “简单” 属性
public static boolean isSimpleProperty(Class<?> type) { Assert.notNull(type, "'type' must not be null"); // clazz是简单值类型 || ( clazz是数组 && clazz的组件类型为简单值类型) // getComponentType:返回数组的组件类型,例如: String[] 返回 String.class,如果是非数组,则返回null return isSimpleValueType(type) || (type.isArray() && isSimpleValueType(type.getComponentType())); } public static boolean isSimpleValueType(Class<?> type) { return (Void.class != type && void.class != type && (ClassUtils.isPrimitiveOrWrapper(type) || Enum.class.isAssignableFrom(type) || CharSequence.class.isAssignableFrom(type) || Number.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type) || Temporal.class.isAssignableFrom(type) || URI.class == type || URL.class == type || Locale.class == type || Class.class == type)); } public static boolean isPrimitiveOrWrapper(Class<?> clazz) { Assert.notNull(clazz, "Class must not be null"); // clazz为基础类型 或者 clazz是基础类型的封装类 return (clazz.isPrimitive() || isPrimitiveWrapper(clazz)); } public static boolean isPrimitiveWrapper(Class<?> clazz) { Assert.notNull(clazz, "Class must not be null"); // 检查clazz是否为8种基础类型的包装类 // primitiveWrapperTypeMap缓存包含8种基础类型和包装类的映射,例如:Integer.class -> int.class return primitiveWrapperTypeMap.containsKey(clazz); } static { primitiveWrapperTypeMap.put(Boolean.class, boolean.class); primitiveWrapperTypeMap.put(Byte.class, byte.class); primitiveWrapperTypeMap.put(Character.class, char.class); primitiveWrapperTypeMap.put(Double.class, double.class); primitiveWrapperTypeMap.put(Float.class, float.class); primitiveWrapperTypeMap.put(Integer.class, int.class); primitiveWrapperTypeMap.put(Long.class, long.class); primitiveWrapperTypeMap.put(Short.class, short.class); primitiveWrapperTypeMap.put(Void.class, void.class); }

containsBean

  • 检测是否存在与 propertyName 相关的 bean 或 BeanDefinition是否存在。
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory { @Override public boolean containsBean(String name) { // 1.将name转换为真正的beanName String beanName = transformedBeanName(name); // 2.检查singletonObjects缓存和beanDefinitionMap缓存中是否存在beanName if (containsSingleton(beanName) || containsBeanDefinition(beanName)) { // 3.name不带&前缀,或者是FactoryBean,则返回true return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name)); } // Not found -> check parent. // 4.没有找到则检查parentBeanFactory BeanFactory parentBeanFactory = getParentBeanFactory(); return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name))); } }

autowireByType

  • 解析 autowireByType 的注入
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected void autowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { //获取的属性类型转换器 TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } //用来存放解析的要注入的属性名 Set<String> autowiredBeanNames = new LinkedHashSet<>(4); //获取要注入的属性名称(非简单属性(8种原始类型、字符、URL等都是简单属性)) String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { try { //获取指定属性名称的属性Descriptor(Descriptor用来记载属性的getter setter type等情况) PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); // Don't try autowiring by type for type Object: never makes sense, // even if it technically is a unsatisfied, non-simple property. //不对Object类型的属性进行装配注入,技术上没法实现,并且没有意义 //即如果属性类型为 Object,则忽略,不做解析 if (Object.class != pd.getPropertyType()) { // 获取指定属性的set方法,封装成MethodParameter(必须有set方法才能通过属性来注入) MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // Do not allow eager init for type matching in case of a prioritized post-processor. // 对于继承了PriorityOrdered的post-processor,不允许立即初始化(热加载) boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered); // 创建一个要被注入的依赖描述,方便提供统一的访问 // 将MethodParameter的方法参数索引信息封装成DependencyDescriptor DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); //根据容器的BeanDefinition解析依赖关系,返回所有要被注入的Bean实例 //解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中 Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { // 将解析出的 bean 存入到属性值列表pvs中 pvs.add(propertyName, autowiredArgument); } for (String autowiredBeanName : autowiredBeanNames) { // 注册依赖关系,beanName依赖autowiredBeanName registerDependentBean(autowiredBeanName, beanName); if (logger.isTraceEnabled()) { logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'"); } } //清除已注入属性的记录 autowiredBeanNames.clear(); } } catch (BeansException ex) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } } }
  • 寻找 bw 中需要依赖注入的属性。

  • 解析当前属性所匹配的 bean 实例,并把解析到的 bean 实例的 beanName 存储在 autowiredBeanNames 中。

  • 注册依赖关系,beanName 依赖 autowiredBeanName。

applyPropertyValues

  • 最终将属性注入到Bean的Wrapper实例里,这里的注入主要是供显式配置了autowiredbyName或者ByType的属性注入。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { if (pvs.isEmpty()) { return; } if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) { //设置安全上下文,JDK安全机制 ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); } MutablePropertyValues mpvs = null; List<PropertyValue> original; // 1.获取属性值列表 if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; // 1.1 如果mpvs中的值已经被转换为对应的类型,那么可以直接设置到BeanWrapper中 if (mpvs.isConverted()) { // Shortcut: use the pre-converted values as-is. try { bw.setPropertyValues(mpvs); return; } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } original = mpvs.getPropertyValueList(); } else { // 1.2 如果pvs并不是使用MutablePropertyValues封装的类型,那么直接使用原始的属性获取方法 original = Arrays.asList(pvs.getPropertyValues()); } TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } // 2.1 获取对应的解析器 BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); // Create a deep copy, resolving any references for values. // 2.2 创建深层拷贝副本,用于存放解析后的属性值 List<PropertyValue> deepCopy = new ArrayList<>(original.size()); boolean resolveNecessary = false; // 3.遍历属性,将属性转换为对应类的对应属性的类型 for (PropertyValue pv : original) { if (pv.isConverted()) { // 3.1 如果pv已经包含转换的值,则直接添加到deepCopy deepCopy.add(pv); } else { // 3.2 否则,进行转换 // 3.2.1 拿到pv的原始属性名和属性值 String propertyName = pv.getName(); Object originalValue = pv.getValue(); if (originalValue == AutowiredPropertyMarker.INSTANCE) { Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod(); if (writeMethod == null) { throw new IllegalArgumentException("Autowire marker for property without write method: " + pv); } originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true); } // 3.2.2 使用解析器解析原始属性值 Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); Object convertedValue = resolvedValue; // 3.2.3 判断该属性是否可转换 boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName); if (convertible) { // 3.2.4 如果可转换,则转换指定目标属性的给定值 convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter); } // Possibly store converted value in merged bean definition, // in order to avoid re-conversion for every created bean instance. // 3.2.5 在合并的BeanDefinition中存储转换后的值,以避免为每个创建的bean实例重新转换 if (resolvedValue == originalValue) { if (convertible) { pv.setConvertedValue(convertedValue); } deepCopy.add(pv); } else if (convertible && originalValue instanceof TypedStringValue && !((TypedStringValue) originalValue).isDynamic() && !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) { pv.setConvertedValue(convertedValue); deepCopy.add(pv); } else { resolveNecessary = true; deepCopy.add(new PropertyValue(pv, convertedValue)); } } } if (mpvs != null && !resolveNecessary) { mpvs.setConverted(); } // Set our (possibly massaged) deep copy. try { // 4.设置bean的属性值为deepCopy bw.setPropertyValues(new MutablePropertyValues(deepCopy)); } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } }

initializeBean

对bean进行初始化

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) { // 1.激活Aware方法 if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareMethods(beanName, bean); return null; }, getAccessControlContext()); } else { invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { // 2.在初始化前应用BeanPostProcessor的postProcessBeforeInitialization方法,允许对bean实例进行包装 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { // 3.调用初始化方法 invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { // 4.在初始化后应用BeanPostProcessor的postProcessAfterInitialization方法,允许对bean实例进行包装 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } // 5.返回wrappedBean return wrappedBean; } }

invokeAwareMethods

  • 激活 Aware方法
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { private void invokeAwareMethods(final String beanName, final Object bean) { if (bean instanceof Aware) { // BeanNameAware: 实现此接口的类想要拿到beanName,因此我们在这边赋值给它 if (bean instanceof BeanNameAware) { ((BeanNameAware) bean).setBeanName(beanName); } // BeanClassLoaderAware:实现此接口的类想要拿到beanClassLoader,因此我们在这边赋值给它 if (bean instanceof BeanClassLoaderAware) { ClassLoader bcl = getBeanClassLoader(); if (bcl != null) { ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl); } } // BeanFactoryAware: 实现此接口的类想要拿到 BeanFactory,因此我们在这边赋值给它 if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this); } } } }

如果对 Spring 比较熟悉的同学应该知道,以 Aware 为结尾的类都是一些扩展接口,用于提供给开发者获取到 BeanFactory 中的一些属性或对象。

applyBeanPostProcessorsBeforeInitialization

  • 在初始化前应用后置处理器 BeanPostProcessor 的 postProcessBeforeInitialization 方法,允许对 bean 实例进行包装。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { @Override public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; // 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessBeforeInitialization方法 for (BeanPostProcessor processor : getBeanPostProcessors()) { // 2.在bean初始化方法执行前,调用postProcessBeforeInitialization方法 Object current = processor.postProcessBeforeInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; } }

postProcessBeforeInitialization

在 bean 初始化前,调用所有 BeanPostProcessors 的 postProcessBeforeInitialization 方法,这个在很早之前就说过了。这边提一个比较重要的实现类:ApplicationContextAwareProcessor。

class ApplicationContextAwareProcessor implements BeanPostProcessor { private final ConfigurableApplicationContext applicationContext; private final StringValueResolver embeddedValueResolver; @Override @Nullable public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware || bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware || bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){ return bean; } AccessControlContext acc = null; if (System.getSecurityManager() != null) { acc = this.applicationContext.getBeanFactory().getAccessControlContext(); } if (acc != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareInterfaces(bean); return null; }, acc); } else { // 调用Aware接口 invokeAwareInterfaces(bean); } return bean; } private void invokeAwareInterfaces(Object bean) { if (bean instanceof EnvironmentAware) { ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); } if (bean instanceof EmbeddedValueResolverAware) { ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver); } if (bean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); } if (bean instanceof ApplicationEventPublisherAware) { ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext); } if (bean instanceof MessageSourceAware) { ((MessageSourceAware) bean).setMessageSource(this.applicationContext); } // ApplicationContextAware:实现此接口的类想要拿到ApplicationContext,因此我们在这边赋值给它 if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); } } }

我们经常通过实现 ApplicationContextAware 接口来拿到 ApplicationContext,我们之所以能拿到 ApplicationContext,就是在这边被赋值的。

invokeInitMethods

  • 调用初始化方法
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd) throws Throwable { //如果当前bean是 InitializingBean类型的&&afterPropertiesSet这个方法没有注册为外部管理的初始化方法 //就回调afterPropertiesSet方法 boolean isInitializingBean = (bean instanceof InitializingBean); if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (logger.isTraceEnabled()) { logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); } // 调用afterPropertiesSet方法 if (System.getSecurityManager() != null) { try { AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> { ((InitializingBean) bean).afterPropertiesSet(); return null; }, getAccessControlContext()); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { ((InitializingBean) bean).afterPropertiesSet(); } } if (mbd != null && bean.getClass() != NullBean.class) { String initMethodName = mbd.getInitMethodName(); //如果设置了initMethod方法的话也会执行用户配置的初始话方法 //并且这个类不是 InitializingBean类型和不是afterPropertiesSet方法 ; //才能执行用户配置的方法 if (StringUtils.hasLength(initMethodName) && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { // 调用自定义初始化方法 invokeCustomInitMethod(beanName, bean, mbd); } } } }

invokeCustomInitMethod

  • 调用自定义初始化方法
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { // 1.拿到初始化方法的方法名 String initMethodName = mbd.getInitMethodName(); Assert.state(initMethodName != null, "No init method set"); // 2.根据方法名拿到方法 Method initMethod = (mbd.isNonPublicAccessAllowed() ? BeanUtils.findMethod(bean.getClass(), initMethodName) : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName)); if (initMethod == null) { // 3.如果不存在initMethodName对应的方法,并且是强制执行初始化方法(默认为强制), 则抛出异常 if (mbd.isEnforceInitMethod()) { throw new BeanDefinitionValidationException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'"); } else { // 如果设置了非强制,找不到则直接返回 if (logger.isTraceEnabled()) { logger.trace("No default init method named '" + initMethodName + "' found on bean with name '" + beanName + "'"); } // Ignore non-existent default lifecycle methods. return; } } if (logger.isTraceEnabled()) { logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'"); } Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod); // 4.调用初始化方法 if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { ReflectionUtils.makeAccessible(methodToInvoke); return null; }); try { AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> methodToInvoke.invoke(bean), getAccessControlContext()); } catch (PrivilegedActionException pae) { InvocationTargetException ex = (InvocationTargetException) pae.getException(); throw ex.getTargetException(); } } else { try { ReflectionUtils.makeAccessible(methodToInvoke); methodToInvoke.invoke(bean); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } }

applyBeanPostProcessorsAfterInitialization

  • 在初始化后应用BeanPostProcessor的postProcessAfterInitialization方法,允许对bean实例进行包装。
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { @Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; // 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessAfterInitialization方法 for (BeanPostProcessor processor : getBeanPostProcessors()) { // 2.在bean初始化后,调用postProcessAfterInitialization方法 Object current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { // 3.如果返回null,则不会调用后续的BeanPostProcessors return result; } result = current; } return result; } }

registerDisposableBeanIfNecessary

  • 注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor。
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory { protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) { AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null); // 1.mbd的scope不是prototype && 给定的bean需要在关闭时销毁 if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { if (mbd.isSingleton()) { // Register a DisposableBean implementation that performs all destruction // work for the given bean: DestructionAwareBeanPostProcessors, // DisposableBean interface, custom destroy method. // 2.单例模式下注册用于销毁的bean到disposableBeans缓存,执行给定bean的所有销毁工作: // DestructionAwareBeanPostProcessors,DisposableBean接口,自定义销毁方法 // 2.1 DisposableBeanAdapter:使用DisposableBeanAdapter来封装用于销毁的bean registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } else { // 3.自定义scope处理 // A bean with a custom scope... Scope scope = this.scopes.get(mbd.getScope()); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'"); } scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc)); } } } }

requiresDestruction

  • 判断给定的 bean 是否需要在关闭时销毁
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory { protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) { // 1.DisposableBeanAdapter.hasDestroyMethod(bean, mbd):判断bean是否有destroy方法 // 2.hasDestructionAwareBeanPostProcessors():判断当前BeanFactory是否注册过DestructionAwareBeanPostProcessor // 3.DisposableBeanAdapter.hasApplicableProcessors:是否存在适用于bean的DestructionAwareBeanPostProcessor return (bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors())))); } }

hasDestroyMethod

  • DisposableBeanAdapter.hasDestroyMethod(bean, mbd):判断 bean 是否有 destroy 方法。
class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable { public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) { if (bean instanceof DisposableBean || bean instanceof AutoCloseable) { // 1.如果bean实现了DisposableBean接口 或者 bean是AutoCloseable实例,则返回true return true; } // 2.拿到bean自定义的destroy方法名 String destroyMethodName = beanDefinition.getDestroyMethodName(); if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName)) { // 3.如果自定义的destroy方法名为“(inferred)”(该名字代表需要我们自己去推测destroy的方法名), // 则检查该bean是否存在方法名为“close”或“shutdown”的方法,如果存在,则返回true return (ClassUtils.hasMethod(bean.getClass(), CLOSE_METHOD_NAME) || ClassUtils.hasMethod(bean.getClass(), SHUTDOWN_METHOD_NAME)); } // 4.如果destroyMethodName不为空,则返回true return StringUtils.hasLength(destroyMethodName); } }

如果 bean 实现了 DisposableBean 接口或 bean 是 AutoCloseable 实例,则返回 true,因为这两个接口都有关闭的方法

hasApplicableProcessors

  • DisposableBeanAdapter.hasApplicableProcessors:是否存在适用于 bean 的 DestructionAwareBeanPostProcessor。
class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable { public static boolean hasApplicableProcessors(Object bean, List<BeanPostProcessor> postProcessors) { if (!CollectionUtils.isEmpty(postProcessors)) { // 1.遍历所有的BeanPostProcessor for (BeanPostProcessor processor : postProcessors) { // 2.如果processor是DestructionAwareBeanPostProcessor if (processor instanceof DestructionAwareBeanPostProcessor) { DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor; if (dabpp.requiresDestruction(bean)) { // 3.如果给定的bean实例需要通过此后处理器进行销毁,则返回true return true; } } } } return false; } }

DisposableBeanAdapter

  • 使用 DisposableBeanAdapter 来封装用于销毁的 bean。
class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable { public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition beanDefinition, List<BeanPostProcessor> postProcessors, @Nullable AccessControlContext acc) { Assert.notNull(bean, "Disposable bean must not be null"); this.bean = bean; this.beanName = beanName; // 1.判断bean是否需要调用DisposableBean的destroy方法 this.invokeDisposableBean = (this.bean instanceof DisposableBean && !beanDefinition.isExternallyManagedDestroyMethod("destroy")); this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed(); this.acc = acc; // 2.拿到自定义的destroy方法名 String destroyMethodName = inferDestroyMethodIfNecessary(bean, beanDefinition); if (destroyMethodName != null && !(this.invokeDisposableBean && "destroy".equals(destroyMethodName)) && !beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) { this.destroyMethodName = destroyMethodName; // 3.拿到自定义的destroy方法 Method destroyMethod = determineDestroyMethod(destroyMethodName); if (destroyMethod == null) { if (beanDefinition.isEnforceDestroyMethod()) { // 4.如果destroy方法名为空,并且enforceDestroyMethod为true,则抛出异常 throw new BeanDefinitionValidationException("Could not find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName + "'"); } } else { // 5.拿到destroy方法的参数类型数组 Class<?>[] paramTypes = destroyMethod.getParameterTypes(); if (paramTypes.length > 1) { // 6.如果destroy方法的参数大于1个,则抛出异常 throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" + beanName + "' has more than one parameter - not supported as destroy method"); } else if (paramTypes.length == 1 && boolean.class != paramTypes[0]) { // 7.如果destroy方法的参数为1个,并且该参数的类型不为boolean,则抛出异常 throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" + beanName + "' has a non-boolean parameter - not supported as destroy method"); } destroyMethod = ClassUtils.getInterfaceMethodIfPossible(destroyMethod); } //赋值给this.destroyMethod this.destroyMethod = destroyMethod; } // 8.查找DestructionAwareBeanPostProcessors,并赋值给this.beanPostProcessors this.beanPostProcessors = filterPostProcessors(postProcessors, bean); } }

inferDestroyMethodIfNecessary

  • 拿到自定义的 destroy 方法名。
class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable { @Nullable private String inferDestroyMethodIfNecessary(Object bean, RootBeanDefinition beanDefinition) { // 1.拿到beanDefinition的destroy方法名 String destroyMethodName = beanDefinition.getDestroyMethodName(); // 2.如果destroy方法名为“(inferred)”|| destroyMethodName为null,并且bean是AutoCloseable实例 if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) || (destroyMethodName == null && bean instanceof AutoCloseable)) { // Only perform destroy method inference or Closeable detection // in case of the bean not explicitly implementing DisposableBean // 3.如果bean没有实现DisposableBean接口,则尝试推测destroy方法的名字 if (!(bean instanceof DisposableBean)) { try { // 4.尝试在bean中寻找方法名为close的方法作为destroy方法 return bean.getClass().getMethod(CLOSE_METHOD_NAME).getName(); } catch (NoSuchMethodException ex) { try { // 5.尝试在bean中寻找方法名为close的方法作为shutdown方法 return bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName(); } catch (NoSuchMethodException ex2) { // no candidate destroy method found } } } // 6.如果没有找到,则返回null return null; } return (StringUtils.hasLength(destroyMethodName) ? destroyMethodName : null); } }

filterPostProcessors

  • 查找 DestructionAwareBeanPostProcessors,并赋值给 beanPostProcessors。
class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable { @Nullable private List<DestructionAwareBeanPostProcessor> filterPostProcessors(List<BeanPostProcessor> processors, Object bean) { List<DestructionAwareBeanPostProcessor> filteredPostProcessors = null; if (!CollectionUtils.isEmpty(processors)) { filteredPostProcessors = new ArrayList<>(processors.size()); // 1.遍历所有的BeanPostProcessor for (BeanPostProcessor processor : processors) { // 2.如果processor是DestructionAwareBeanPostProcessor if (processor instanceof DestructionAwareBeanPostProcessor) { DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor; if (dabpp.requiresDestruction(bean)) { // 3.如果给定的bean实例需要通过此后处理器进行销毁,则添加到filteredPostProcessors filteredPostProcessors.add(dabpp); } } } } return filteredPostProcessors; } }

总结

至此,finishBeanFactoryInitialization 方法解析完毕,在 finishBeanFactoryInitialization 方法中,我们主要做了以下操作:

  • 将之前解析的 BeanDefinition 进一步处理,将有父 BeanDefinition 的进行合并,获得 MergedBeanDefinition
  • 尝试从缓存获取 bean 实例
  • 处理特殊的 bean —— FactoryBean 的创建
  • 创建 bean 实例
  • 循环引用的处理
  • bean 实例属性填充
  • bean 实例的初始化
  • BeanPostProcessor 的各种扩展应用

finishBeanFactoryInitialization 方法解析的结束,也标志着 Spring IoC 整个构建过程中,重要的内容基本都已经解析完毕。

 

参考: https://zhuanlan.zhihu.com/p/83491006

https://www.imooc.com/article/37039?block_id=tuijian_wz

网友评论