Bean后置处理器 - BeanPostProcessor#postProcessBeforeInitialization

代码片段:

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization

@Override
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;
}

这里能满足的后置处理器, 就比较多了. 调试一下看看:

 

 

 有6个能满足条件, 一个一个来看

 

ApplicationContextAwareProcessor

这个后置处理器, 主要是用来处理一些 Aware 的.

//bean初始化方法调用之前执行此方法, 此处主要是对以下几个 *Aware 进行处理, 调用这些 *Aware 定义的接口方法
@Override
@Nullable
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    AccessControlContext acc = null;

    if (System.getSecurityManager() != null &&
            (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
                    bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
                    bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
        acc = this.applicationContext.getBeanFactory().getAccessControlContext();
    }

    if (acc != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareInterfaces(bean);
            return null;
        }, acc);
    }
    else {
        invokeAwareInterfaces(bean);
    }

    return bean;
}

这里主要看invokeAwareIntefaces方法:

private void invokeAwareInterfaces(Object bean) {
    if (bean instanceof Aware) {
        if (bean instanceof EnvironmentAware) {
            ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
        }
        if (bean instanceof EmbeddedValueResolverAware) {
            ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
        }
        if (bean instanceof ResourceLoaderAware) {
            ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
        }
        if (bean instanceof ApplicationEventPublisherAware) {
            ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
        }
        if (bean instanceof MessageSourceAware) {
            ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
        }
        //spring帮你set一个applicationContext对象
        //所以当我们自己的一个对象实现了ApplicationContextAware对象只需要提供setter就能得到applicationContext对象
        if (bean instanceof ApplicationContextAware) {
            ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
        }
    }
}

 

ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
    if (bean instanceof ImportAware) {
        ImportRegistry ir = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
        AnnotationMetadata importingClass = ir.getImportingClassFor(bean.getClass().getSuperclass().getName());
        if (importingClass != null) {
            ((ImportAware) bean).setImportMetadata(importingClass);
        }
    }
    return bean;
}

这里主要是注入 ImportAware 的. 也是一种 Aware. 

 

PostProcessorRegistrationDelegate$BeanPostProcessorChecker

//初始化之前, 不做任何处理
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
    return bean;
}

这里不做任何处理, 后面貌似, 也只是打印了个日志.

 

CommonAnnotationBeanPostProcessor

其实现由父类完成:

org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
    try {
        metadata.invokeInitMethods(bean, beanName);
    }
    catch (InvocationTargetException ex) {
        throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
    }
    return bean;
}

findLifecycleMetadata 在 MergedBeanDefinitionPostProcessor 的时候, 就执行过了. 这里也是相当于从缓存中拿取.

拿到 @PostConstructor 对应的方法集合, 进行循环调用.

这里能看到 @PostConstructor 的调用时机, 是初始化(invokeInitMethods - 这里面会调用InitializingBean#afterPropertiesSet() 和用户自定义的init-method初始化方法 )之前.

 

AutowiredAnnotationBeanPostProcessor

由父类实现:

org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter#postProcessBeforeInitialization

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    return bean;
}

里面啥也没干

 

ApplicationListenerDetector

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
    return bean;
}

这里也是啥也没干

 

从这里看, 虽然他有6个后置处理器, 但是真正起作用的, 就一下几个:

1. ApplicationContextAwareProcessor - 处理几个 Aware

2. ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor - 处理 ImportAware

3. CommonAnnotationBeanPostProcessor - 调用 @PostConstructor 对于方法集

 

posted @ 2020-07-27 21:29  Sniper_ZL  阅读(2156)  评论(0编辑  收藏  举报