码迷,mamicode.com
首页 > 编程语言 > 详细

Spring注解之BeanPostProcessor与InitializingBean

时间:2018-05-18 13:45:08      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:包装   注解   实例化   text   autowire   on()   cto   实例   实现   

/**
*  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

标签:包装   注解   实例化   text   autowire   on()   cto   实例   实现   

原文地址:https://www.cnblogs.com/liaojie970/p/9055579.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!