Spring注解系列十五:生命周期-BeanPostProcessor原理

1、AbstractAutowireCapableBeanFactory

//在bean初始化之前给bean进行属性赋值
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
   PropertyValues pvs = mbd.getPropertyValues();
     if (bw == null) {
         if (!((PropertyValues)pvs).isEmpty()) {
             throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
         }
     } else {
         boolean continueWithPropertyPopulation = true;
         if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
             Iterator var6 = this.getBeanPostProcessors().iterator();

             while(var6.hasNext()) {
                 BeanPostProcessor bp = (BeanPostProcessor)var6.next();
                 if (bp instanceof InstantiationAwareBeanPostProcessor) {
                     InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
                     if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                         continueWithPropertyPopulation = false;
                         break;
                     }
                 }
             }
         }

         if (continueWithPropertyPopulation) {
             if (mbd.getResolvedAutowireMode() == 1 || mbd.getResolvedAutowireMode() == 2) {
                 MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs);
                 if (mbd.getResolvedAutowireMode() == 1) {
                     this.autowireByName(beanName, mbd, bw, newPvs);
                 }

                 if (mbd.getResolvedAutowireMode() == 2) {
                     this.autowireByType(beanName, mbd, bw, newPvs);
                 }

                 pvs = newPvs;
             }

             boolean hasInstAwareBpps = this.hasInstantiationAwareBeanPostProcessors();
             boolean needsDepCheck = mbd.getDependencyCheck() != 0;
             if (hasInstAwareBpps || needsDepCheck) {
                 PropertyDescriptor[] filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                 if (hasInstAwareBpps) {
                     Iterator var9 = this.getBeanPostProcessors().iterator();

                     while(var9.hasNext()) {
                         BeanPostProcessor bp = (BeanPostProcessor)var9.next();
                         if (bp instanceof InstantiationAwareBeanPostProcessor) {
                             InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
                             pvs = ibp.postProcessPropertyValues((PropertyValues)pvs, filteredPds, bw.getWrappedInstance(), beanName);
                             if (pvs == null) {
                                 return;
                             }
                         }
                     }
                 }

                 if (needsDepCheck) {
                     this.checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs);
                 }
             }

             this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs);
         }
     }
 }

//初始化bean
 protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
   if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                AbstractAutowireCapableBeanFactory.this.invokeAwareMethods(beanName, bean);
                return null;
            }
        }, this.getAccessControlContext());
    } else {
        this.invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
    	//在初始化之前工作
        wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
    }

    try {
    	//执行自定义初始化
        this.invokeInitMethods(beanName, wrappedBean, mbd);
    } catch (Throwable var6) {
        throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
    }

    if (mbd == null || !mbd.isSynthetic()) {
    	//在初始化之后工作
        wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}


//执行初始化
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable {
    boolean isInitializingBean = bean instanceof InitializingBean;
    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
        }

        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    public Object run() throws Exception {
                        ((InitializingBean)bean).afterPropertiesSet();
                        return null;
                    }
                }, this.getAccessControlContext());
            } catch (PrivilegedActionException var6) {
                throw var6.getException();
            }
        } else {
            ((InitializingBean)bean).afterPropertiesSet();
        }
    }

    if (mbd != null) {
        String initMethodName = mbd.getInitMethodName();
        if (initMethodName != null && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) {
            this.invokeCustomInitMethod(beanName, bean, mbd);
        }
    }

}


//初始化之前
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
   Object result = existingBean;
    Iterator var4 = this.getBeanPostProcessors().iterator();


	//遍历得到容器中所有的BeanPostProcessor
    do {
        if (!var4.hasNext()) {
            return result;
        }

        BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next();
        //执行postProcessorsBeforeInitialization方法,一但返回null,跳出for循环。
        result = beanProcessor.postProcessBeforeInitialization(result, beanName);
    } while(result != null);

    return result;
}


//初始化之后
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
   Object result = existingBean;
    Iterator var4 = this.getBeanPostProcessors().iterator();

    do {
        if (!var4.hasNext()) {
            return result;
        }

        BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next();
        result = beanProcessor.postProcessAfterInitialization(result, beanName);
    } while(result != null);

    return result;
}

猜你喜欢

转载自blog.csdn.net/lizhiqiang1217/article/details/89951406
今日推荐