Spring扩展点之Aware接口族

10次阅读

共计 3399 个字符,预计需要花费 9 分钟才能阅读完成。

引言

Spring 中提供了各种 Aware 接口,方便从上下文中获取当前的运行环境,比较常见的几个子接口有:BeanFactoryAware,BeanNameAware,ApplicationContextAware,EnvironmentAware,BeanClassLoaderAware 等,这些 Aware 的作用都可以从命名得知

Aware处理

其中 BeanNameAwareBeanClassLoaderAwareBeanFactoryAware这三个是直接在 bean 的初始化之前就处理了的,具体代码在 AbstractAutowireCapableBeanFactory.initializeBean 方法中:

protected Object initializeBean(String beanName, Object bean, RootBeanDefinition mbd) {
    // 判断对象实现的接口类型,处理特定的三种接口类型:BeanNameAware、BeanClassLoaderAware 和 BeanFactoryAware。if (bean instanceof BeanNameAware) {((BeanNameAware) bean).setBeanName(beanName);
    }
 
    if (bean instanceof BeanClassLoaderAware) {((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
    }
 
    if (bean instanceof BeanFactoryAware) {((BeanFactoryAware) bean).setBeanFactory(this);
    }
    // 开始 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;
}

除了这三种之外的那些 Aware 接口的实现就不太一样了,它们都是利用 BeanPostProcessor 接口完成的,关于 BeanPostProcessor 接口的原理可以这篇文章:Spring 扩展点之 BeanPostProcessor

ApplicationContextAware 就是利用 ApplicationContextAwareProcessor 实现的:

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;
    }
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);
            }
            if (bean instanceof ApplicationContextAware) {((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
            }
        }
    }

ApplicationContextAwareProcessor 的注册奥秘在 AbstractApplicationContext.prepareBeanFactory 方法中:

beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this));
 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); 
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

正文完
 0