Spring注解之BeanPostProcessor与InitializingBean

Posted 山高我为峰

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring注解之BeanPostProcessor与InitializingBean相关的知识,希望对你有一定的参考价值。

/**
*  BeanPostProcessor 为每个bean实例化时提供个性化的修改,做些包装等
*/ package org.springframework.beans.factory.config; import org.springframework.beans.BeansException; public interface BeanPostProcessor { /** * 在bean实例化前调用*/ Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; /** * 在bean实例化后调用,如果bean实现了InitializingBean,则在执行完* 该接口的afterPropertiesSet方法后调用 ,如果实现了init-method则 * 在执行完init-method后调用*/ Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; }
package org.springframework.beans.factory;

/**
 /* *InitializingBean 为实现该接口的bean提供默认的初始化方法 *也可以在xml配置bean的使用init-method来实现初始化方法 */*/
public interface InitializingBean {

    void afterPropertiesSet() throws Exception;

}

InitializingBean和BeanPostProcessor的执行顺序:构造方法-->BeanPostProcessor-->InitializingBean-->bean中的初始化方法

bean的最终初始化是由AbstractAutowireCapableBeanFactory的initializeBean方法来完成的,下面是该方法的源码

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

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = **applyBeanPostProcessorsBeforeInitialization**(wrappedBean, beanName);
        }

        try {
            **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()) {
            wrappedBean = **applyBeanPostProcessorsAfterInitialization**(wrappedBean, beanName);
        }
        return wrappedBean;
    }

可以看到initializeBean主要有四步骤 
1. invokeAwareMethods 调用实现Aware接口方法,这里只针对三种Aware接口BeanNameAware,BeanClassLoaderAware,BeanFactoryAware,方法如下

private void invokeAwareMethods(final String beanName, final Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
            }
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }
  1. applyBeanPostProcessorsBeforeInitialization 调用所有实现BeanPostProcessor类 的 postProcessBeforeInitialization方法,源码如下
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            result = beanProcessor.postProcessBeforeInitialization(result, beanName);
            if (result == null) {
                return result;
            }
        }
        return result;
    }
  1. invokeInitMethods 调用bean的初始化方法,如果bean实现了InitializingBean 接口,则调用afterPropertiesSet方法,如果有配置init-method,则调用配置的初始化方法,源码如下:
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 (logger.isDebugEnabled()) {
                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;
                        }
                    }, getAccessControlContext());
                }
                catch (PrivilegedActionException pae) {
                    throw pae.getException();
                }
            }               
            else {
                ((InitializingBean) bean).**afterPropertiesSet**();
            }
        }

        if (mbd != null) {
            String initMethodName = mbd.getInitMethodName();
            if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                    !mbd.isExternallyManagedInitMethod(initMethodName)) {
                **invokeCustomInitMethod**(beanName, bean, mbd);
            }
        }
    }
  1. applyBeanPostProcessorsAfterInitialization 调用所有实现BeanPostProcessor类 的 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;
    }

注:https://blog.csdn.net/zhaiyang1992/article/details/52200602

 





以上是关于Spring注解之BeanPostProcessor与InitializingBean的主要内容,如果未能解决你的问题,请参考以下文章

Spring之IOC-注解方式

Spring注解之组件注册

spring开发之注解基础(半注解半xml)

JavaEE开发之Spring中的条件注解组合注解与元注解

Spring注解之实体类常用注解

spring之注解概述