• spring源码 - bean的实例化过程


    在整个bean实例化过程中以下类启非常重要的作用,主要用于收集beanfactory中是存在相对接口实现类

    static class BeanPostProcessorCache {
       final List<InstantiationAwareBeanPostProcessor> instantiationAware = new ArrayList<>();
       final List<SmartInstantiationAwareBeanPostProcessor> smartInstantiationAware = new ArrayList<>();
       final List<DestructionAwareBeanPostProcessor> destructionAware = new ArrayList<>();
       final List<MergedBeanDefinitionPostProcessor> mergedDefinition = new ArrayList<>();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这个类有非常重要的作用,在bean的实例化各个阶段都会确认spring中是否包含了相关类,穿插在各个阶段使用,主要是通过以下方法来初始化此类:

    BeanPostProcessorCache getBeanPostProcessorCache() {
       BeanPostProcessorCache bpCache = this.beanPostProcessorCache;
       if (bpCache == null) {
          bpCache = new BeanPostProcessorCache();
          for (BeanPostProcessor bp : this.beanPostProcessors) {
             if (bp instanceof InstantiationAwareBeanPostProcessor) {
                bpCache.instantiationAware.add((InstantiationAwareBeanPostProcessor) bp);
                if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                   bpCache.smartInstantiationAware.add((SmartInstantiationAwareBeanPostProcessor) bp);
                }
             }
             if (bp instanceof DestructionAwareBeanPostProcessor) {
                bpCache.destructionAware.add((DestructionAwareBeanPostProcessor) bp);
             }
             if (bp instanceof MergedBeanDefinitionPostProcessor) {
                bpCache.mergedDefinition.add((MergedBeanDefinitionPostProcessor) bp);
             }
          }
          this.beanPostProcessorCache = bpCache;
       }
       return bpCache;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    初始化前执行逻辑:

    1. 先执行instantiationAware中对象的postProcessBeforeInstantiation方法

    protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
       for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
          Object result = bp.postProcessBeforeInstantiation(beanClass, beanName);
          if (result != null) {
             return result;
          }
       }
       return null;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.如查1中返回的不为null,执行beanPostProcessors对象中的postProcessAfterInitialization方法

    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
          throws BeansException {
    
       Object result = existingBean;
    
       for (BeanPostProcessor processor : getBeanPostProcessors()) {
          Object current = processor.postProcessAfterInitialization(result, beanName);
          if (current == null) {
             return result;
          }
          result = current;
       }
       return result;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    经过1和2如果bean通过InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation方法正常生成后继就可以不用执行。
    扩展点:
    如果你不想让框架自已生成的BEAN,可以自定义实现InstantiationAwareBeanPostProcessor接口类来现

    3.将beforeInstantiationResolved赋值为true,如果2中返回的bean不为null,否则设为false

    protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
       Object bean = null;
       if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
          // Make sure bean class is actually resolved at this point.      
          if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
             Class<?> targetType = determineTargetType(beanName, mbd);
             if (targetType != null) {
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                   bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
             }
          }
          mbd.beforeInstantiationResolved = (bean != null);
       }
       return bean;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    经过以上步骤如果bean不为空说明bean生成结束,不进行以下步骤

    4.如果经过前面的1、2、3过程之后bean为空,找出前面的

    SmartInstantiationAwareBeanPostProcessor对象执行determineCandidateConstructors得到beanclass的构造函数
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
          throws BeansException {
    
       if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
          for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
             Constructor<?>[] ctors = bp.determineCandidateConstructors(beanClass, beanName);
             if (ctors != null) {
                return ctors;
             }
          }
       }
       return null;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    扩展点:
    这里可以干涉bean实际生成的构造函数

    5.通过调用构造函数生成BeanWrapperImpl对象

    if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
          mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
       return autowireConstructor(beanName, mbd, ctors, args);
    }
    // Preferred constructors for default construction?
    ctors = mbd.getPreferredConstructors();
    if (ctors != null) {
       return autowireConstructor(beanName, mbd, ctors, null);
    } 
    return instantiateBean(beanName, mbd);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    生成BeanWrapper对象并注册CustomEdit,spring主要提供基础类型的
    到这里bean对象已生成

    6.bean生成后执行MergedBeanDefinitionPostProcessor对象的postProcessMergedBeanDefinition方法

    protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
       for (MergedBeanDefinitionPostProcessor processor : getBeanPostProcessorCache().mergedDefinition) {
          processor.postProcessMergedBeanDefinition(mbd, beanType, beanName);
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在里只能对beandefintion.beanType、beanName最后的处理

    在spring内部的ApplicationListenerDetector类的逻辑,主要看bean是否实现了ApplicationListener接口

    public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
       if (ApplicationListener.class.isAssignableFrom(beanType)) {
          this.singletonNames.put(beanName, beanDefinition.isSingleton());
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    7.将生成的bean经过beanfactory中SmartInstantiationAwareBeanPostProcessor接口对象方法getEarlyBeanReference处理放入singletonFactories属性中

    以下过程是进行实例化对象的属性性填充

    8.执行populateBean方法

    1. 执行beanfactory中拥有InstantiationAwareBeanPostProcessor对象postProcessAfterInstantiation方法,如果不是返回true退出
      扩展点: 这里干涉给bean属性填值
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
       for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
          if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
             return;
          }
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    1. 执行autowired有关内容
    2. 查看beanfactory中是否有InstantiationAwareBeanPostProcessor类对象,如有执行postProcessProperties方法,返回PropertyValues对象,如果为空在执行其postProcessPropertyValues方法
            for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {  
       PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
       if (pvsToUse == null) {
          if (filteredPds == null) {
             filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
          }
          pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
          if (pvsToUse == null) {
             return;
          }
       }
       pvs = pvsToUse;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    扩展点:
    这里可以干涉PropertyValue的值,通过实现InstantiationAwareBeanPostProcessor 接口的postProcessPropertyValues方法

    4)进行bean属性赋值
    if (pvs != null) {
    applyPropertyValues(beanName, mbd, bw, pvs);
    }

    9.执行initializeBean(beanName, exposedObject, mbd)方法

    1) 执行invokeAwareMethods方法,确认bean是否为BeanNameAware、BeanClassLoaderAware、BeanFactoryAware三个接口实现类,若是执行对应方法

    private void invokeAwareMethods(String beanName, Object bean) {
       if (bean instanceof Aware) {
          if (bean instanceof BeanNameAware) {
             ((BeanNameAware) bean).setBeanName(beanName);
          }
          if (bean instanceof BeanClassLoaderAware) {
             ClassLoader bcl = getBeanClassLoader();
             if (bcl != null) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
             }
          }
          if (bean instanceof BeanFactoryAware) {
             ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
          }
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    扩展点:
    这里可以修改自已的bean名字,如果bean是BeanNameAware的接口实现

    2)执行applyBeanPostProcessorsBeforeInitialization方法,主要是确认是否beanfactory中实现了BeanPostProcessor接口对象,然后调用其postProcessBeforeInitialization方法
    从下面的代码逻辑可以出调用postProcessBeforeInitialization后,返回值不为null,bean变为其返回的值

    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
          throws BeansException {
    
       Object result = existingBean;
       for (BeanPostProcessor processor : getBeanPostProcessors()) {
          Object current = processor.postProcessBeforeInitialization(result, beanName);
          if (current == null) {
             return result;
          }
          result = current;
       }
       return result;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    这里在启动阶段会调用spring中默认的ApplicationListenerDetector类的postProcessBeforeInitialization方法,主要对于bean是实现ApplicationListener接口类的加入到侦听框架事件中。
    扩展点:
    beanfactory中如果有自定义实现BeanPostProcessor接口类,可以通过postProcessBeforeInitialization方法修改bean有关信息

    10.调用bean的init-method方法

    11.执行beanfactory中实现BeanPostProcessor接口对象的postProcessAfterInitialization方法

    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
          throws BeansException {
    
       Object result = existingBean;
       for (BeanPostProcessor processor : getBeanPostProcessors()) {
          Object current = processor.postProcessAfterInitialization(result, beanName);
          if (current == null) {
             return result;
          }
          result = current;
       }
       return result;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    扩展点:
    这里干涉bean的有关内容

    12.确认bean的销毁有关

    1)bean是否是DisposableBean、AutoCloseable接口实现类
    2)确认bean是否有销毁方法
    3)确认beanfactory中是否有DestructionAwareBeanPostProcessor接口实现类对象,如果并执行其方法requiresDestruction,并返回bool值
    若1、2、3条件都为true,执行以下逻辑注册bean的disposableBeans信息
    registerDisposableBean(beanName, new DisposableBeanAdapter( bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, acc));

  • 相关阅读:
    【Go】用 DBeaver、db browser 和 SqlCipher 读取 SqlCipher 数据库
    经济发展由新技术推动着来
    04MQ消息队列
    lv8 嵌入式开发-网络编程开发 18 广播与组播的实现
    配置公网和私网用户通过非公网口的IP地址访问内部服务器和Internet示例
    华为机试真题 C++ 实现【迷宫问题】
    通过nodeJS如何实现爬虫功能
    有几种人工神经网络算法,人工神经网络算法实例
    [附源码]java毕业设计基于的前端课程学习网站
    Gomodule和GoPath
  • 原文地址:https://blog.csdn.net/lin000_0/article/details/128087504