InstantiationAwareBeanPostProces

2019-06-25  本文已影响0人  爱撒谎的男孩

转载自个人博客https://chenjiabing666.github.io/2019/06/25/InstantiationAwareBeanPostProcessor%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/

简介

Bean加载顺序

InstantiationAwareBeanPostProcessor接口方法的执行顺序

方法解析

/**
* org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation 
* 作用:在实例化之前解析是否有快捷创建的Bean,既是通过postProcessBeforeInstantiation返回的Bean
* 内部调用两个重要的方法:
*   1、applyBeanPostProcessorsBeforeInstantiation:内部遍历调用postProcessBeforeInstantiation方法【在实例化之前调用】
*   2、applyBeanPostProcessorsAfterInitialization:如果postProcessBeforeInstantiation方法返回了快捷的Bean,内部遍历调用postProcessBeforeInstantiation方法【在初始化之后调用】
*/
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) {
                    //调用方法,内部遍历调用postProcessBeforeInstantiation方法【在实例化之前调用】
                    bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                    //如果返回了快捷的Bean
                    if (bean != null) {
                        //如果postProcessBeforeInstantiation方法返回了快捷的Bean,内部遍历调用postProcessBeforeInstantiation方法【在初始化之后调用】
                        bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                    }
                }
            }
            mbd.beforeInstantiationResolved = (bean != null);
        }
        return bean;
    }
    
    /**
    *   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation
    *   作用:调用postProcessBeforeInstantiation方法
    */
    protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName)
                throws BeansException {
            //遍历所有的后置处理器
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                //判断是否是InstantiationAwareBeanPostProcessor类型的,如果是的,调用postProcessBeforeInstantiation方法获取快捷Bean
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
                    if (result != null) {
                        return result;
                    }
                }
            }
            return null;
        }
    
    /**
    *   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization
    *   作用:遍历调用postProcessAfterInitialization
    */
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
                throws BeansException {
            Object result = existingBean;
            for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
                result = beanProcessor.postProcessAfterInitialization(result, beanName);
                if (result == null) {
                    return result;
                }
            }
            return result;
        }
/**
* org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean
* 填充指定Bean的属性
* 在该方法内部遍历所有的BeanPostPorcessor,调用postProcessAfterInstantiation方法
*/
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
        //获取属性
        PropertyValues pvs = mbd.getPropertyValues();
        if (bw == null) {
            if (!pvs.isEmpty()) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            }
            else {
                // Skip property population phase for null instance.
                return;
            }
        }

        //**********************逻辑开始执行********************
        //标志,判断是否继续执行属性填充,默认为false
        boolean continueWithPropertyPopulation = true;
        //判断ioc容器中是否存在InstantiationAwareBeanPostProcessors(
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            //遍历所有的BeanPostProcessor
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                //判断类型是InstantiationAwareBeanPostProcessor
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    //执行postProcessAfterInstantiation方法
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        //返回结果为false,那么赋值continueWithPropertyPopulation=false,表示不继续执行属性填充
                        continueWithPropertyPopulation = false;
                        break;
                    }
                }
            }
        }
        //如果continueWithPropertyPopulation为false,直接返回,不执行下面的步骤
        if (!continueWithPropertyPopulation) {
            return;
        }
        //
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
                mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

            // Add property values based on autowire by name if applicable.
            if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs);
            }

            // Add property values based on autowire by type if applicable.
            if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs);
            }

            pvs = newPvs;
        }

        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

        if (hasInstAwareBpps || needsDepCheck) {
            PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            if (hasInstAwareBpps) {
                //同样是遍历BeanPostProcessor
                for (BeanPostProcessor bp : getBeanPostProcessors()) {
                    if (bp instanceof InstantiationAwareBeanPostProcessor) {
                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                        //执行postProcessPropertyValues方法
                        pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvs == null) {
                            return;
                        }
                    }
                }
            }
            if (needsDepCheck) {
                checkDependencies(beanName, mbd, filteredPds, pvs);
            }
        }
        //重要的一步,设置属性
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
/**
* org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean的代码片段
*/
if (hasInstAwareBpps || needsDepCheck) {
            PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            if (hasInstAwareBpps) {
                //遍历调用postProcessPropertyValues方法
                for (BeanPostProcessor bp : getBeanPostProcessors()) {
                    if (bp instanceof InstantiationAwareBeanPostProcessor) {
                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                        pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        //如果返回的pvs是null,直接返回
                        if (pvs == null) {
                            return;
                        }
                    }
                }
            }
            if (needsDepCheck) {
                checkDependencies(beanName, mbd, filteredPds, pvs);
            }
        }   
        //执行真正的属性填充
        applyPropertyValues(beanName, mbd, bw, pvs);

实例

@Component
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    /**
     * 在实例化之前调用,如果返回null,一切按照正常顺序执行,如果返回的是一个实例的对象,那么这个将会跳过实例化、初始化的过程
     * @param beanClass
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (beanClass == User.class) {
            System.out.println("postProcessBeforeInstantiation执行");
            return null;
        }

        return null;
    }

    /**
     * 在实例化之后,postProcessBeforeInitialization之前执行
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (bean instanceof User) {
            System.out.println("postProcessAfterInstantiation执行");
            return true;
        }

        return true;
    }

    /**
     * 实例化之后调用,属性填充之前
     * @param pvs PropertyValues对象,用于封装指定类的对象,简单来说就是PropertyValue的集合,里面相当于以key-value形式存放类的属性和值
     * @param pds PropertyDescriptor对象数组,PropertyDescriptor相当于存储类的属性,不过可以调用set,get方法设置和获取对应属性的值
     * @param bean 当前的bean
     * @param beanName beanName
     * @return 如果返回null,那么将不会进行后续的属性填充,比如依赖注入等,如果返回的pvs额外的添加了属性,那么后续会填充到该类对应的属性中。
     */
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        if (pvs instanceof MutablePropertyValues&&bean instanceof User){
           MutablePropertyValues mutablePropertyValues= (MutablePropertyValues) pvs;
           HashMap<Object, Object> map = new HashMap<>();
           map.put("name","陈加兵");
           map.put("age",44);
           mutablePropertyValues.addPropertyValues(map);
           return mutablePropertyValues;
        }

        /**使用pds设置值
        if (bean instanceof User) {
            for (PropertyDescriptor descriptor:pds) {
                try {
                    if ("name".equals(descriptor.getName())) {
                        descriptor.getWriteMethod().invoke(bean, "陈加兵");
                    }else if("age".equals(descriptor.getName())){
                        descriptor.getWriteMethod().invoke(bean,40);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return null;
        }**/
        return pvs;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof User) {
            System.out.println("postProcessBeforeInitialization执行");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof User) {
            System.out.println("postProcessAfterInitialization执行");
        }
        return bean;
    }
}

源码梳理

Autowired源码解析

总结

上一篇 下一篇

猜你喜欢

热点阅读