Spring源码初探-IOC(5)-ApplicationContext功能扩展及其扩展点

https://www.jianshu.com/p/2692bf784976

前言

前面几篇关于Spring的文章简单阐述了使用BeanFactory作为容器时bean的初始化过程。然而在实际使用中,我们并不会直接接触和编码BeanFactory,我们通常会使用另外一个功能更强、更完善的容器ApplicationContext。本文粗略讲述了ApplicationContext对于BeanFactory的功能扩展,并将重点放在了Spring在容器启动和初始化过程中提供的扩展点和事件发布上。扩展点让我们能够“插手和干预”Bean的初始化,通过容器发布的事件得以了解容器的一些内部过程。

ApplicationContext的功能扩展

ApplicationContext是“事实上”的容器标准,它基于BeanFactory并对其做了一些功能上的扩展。例如:

  • 通过MessageResource支持国际化
  • 提供了容器内部的消息发布机制
  • 自动添加BeanFactoryPostProcessor、BeanPostProcessor到容器中
    等。
    由于ApplicationContext对于BeanFactory的扩展不是本文阐述的重点,所以略过。

Spring容器初始化中的扩展点

Spring容器初始化中的扩展点不仅包括了Beanfactory提供的也包含了ApplictionContext增强的。

从前面几篇关于容器初始化的文章可以得出,从xml到实例化并初始化完bean大体上经历了两个过程:

  • 容器启动过程:这个过程包括了读取xml文件,并替换一些系统或者自定义变量,将xml标签解析成BeanDefinitionwrapper。
  • 容器初始化过程:这个过程包括了解析BeanDefinition中包含的Bean信息,完成Bean的实例化(Instantiation)和初始化(Initialization)过程。

而ApplicationContext将容器启动和初始化过程细化成了一些模板函数,构成以下步骤。

        public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Prepare the bean factory for use in this context.
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);

                // Initialize message source for this context.
                initMessageSource();

                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();

                // Initialize other special beans in specific context subclasses.
                onRefresh();

                // Check for listener beans and register them.
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                finishRefresh();
            }

            catch (BeansException ex) {
                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }
        }
    }

整个过程及其中的扩展点可以表示成下图:

 

容器启动及初始化过程.jpg

图中表示出了Spring容器中设计到的很多扩展点,主要可以分为以下几类:

  • BeanFactoryPostProcessor
  • 各种Aware
  • BeanPostProcessor
  • 隐藏的一些特殊功能
    下文将一项一项地进行梳理

BeanFactoryPostProcessor

简介

BeanFactoryPostProcessor是一个很重要的接口,其中只有一个方法

void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

它起作用的时机发生在解析成BeanDefinition后,实例化之前。从名字可以看出来,BeanFactoryPostProcessor针对的应该是容器级别的扩展,名为“BeanFactory PostProcessor”即对容器中所有的BeanDefinition都起普遍作用。BeanFactoryPostProcessor有几个我们比较常用的子类PropertyPlaceholderConfigurer、CustomEditorConfigurer,前者用于配置文件中的${var}变量替换,后者用于自定义编辑BeanDefinition中的属性值,合理利用CustomEditorConfigurer会有一些意想不到的效果(例如可以通过修改某些属性实现类似aop的功能)。

使用

如果是在BeanFactory中使用,我们需要

PropertyPlaceholderConfigurer  configurer = new PropertyPlaceholderConfigurer();
configurer.setLaction("xxx");
configurer.postProcessBeanFactory(beanFactory);

很繁琐,很麻烦,而且通常我们并不喜欢硬编码直接使用BeanFactory。在ApplicationContext中得到了改善,使用BeanFactoryPostProcessor只需要在xml文件中进行相应的配置就行,因为ApplicationContext在初始化过程中会调用invokeBeanFactoryPostProcessors(beanFactory),该函数会找出所有BeanFactoryPostProcessor类型的bean,调用postProcessBeanFactory方法。

BeanPostProcessor

简介

BeanPostProcessor很容易和BeanFactoryPostProcessor混淆,但从名字上来说,BeanPostProcessor是“Bean PostProcessor”,主要针对于Bean这一级别,关注的主要是Bean实例化后,初始化前后的。为什么说主要呢?因为存在特例,有一个BeanPostProcessor的调用并不是发生在实例化后,初始化前后。BeanPostProcessor接口存在两个方法,从名字可以看粗一个调用在初始化之前,一个调用在初始化之后。

  Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

BeanPostProcessor在BeanFactory的初始化bean的函数initializeBean中,主要代码为,基本就是取出所有的BeanPostProcessor,然后遍历调用其postProcessBeforeInitialization或者postProcessAfterInitialization方法。

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);
        }

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

使用

Spring利用BeanPostProcessor给了我们在bean初始化前后“doSomething”的机会。
在BeanFactory中使用需要编码

 beanFactory.addBeanPostProcessor(new SomeBeanPostProcessor);

但是在ApplicationContext中,我们只需要将自定义的BeanPostProcessor配置到xml文件中即可。ApplicationContext在初始化过程中会识别所有的BeanPostProcessors并添加到BeanFactory中。

各种Aware

简介

这种类型的扩展点是我们比较熟悉的了,例如ApplicationContextAware、BeanFactoryAware等,Aware的接口用于标识“我需要这个对象”,例如ApplicationContextAware通知容器我需要“当前的ApplicationContext对象”。这个Spring给我们提供的一种用于获取有用对象的一种好的方式。

使用

需要注意的是,Aware起作用的时机是在Bean已经完成实例化之后,初始化Bean的同时。而且需要注意的是BeanFactory对于Aware的处理和ApplicationContext是不同的。

先看BeanFactory中的处理方式,各种Aware被调用的地方是在初始化bean的函数
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;
    }

    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);
            }
        }
    }

可以看到其发生在invokeInitMethods之前。而ApplicationContext怎么处理呢?ApplicationContext本身是利用BeanFactory进行容器的初始化,而BeanFactory却硬编码了invokeAwareMethods中Aware的类型,那ApplicationContext究竟是怎么调用ApplicationContextAware的呢,答案就在函数prepareBeanFactory中,

beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

ApplicationContext为beanFactory增加了ApplicationContextAwareProcessor,ApplicationContextAwareProcessor是一种BeanPostProcessor。前文提到BeanPostProcessor发生在bean初始化前后,在bean初始化之前将调用postProcessBeforeInitialization方法,ApplicationContextAwareProcessor#postProcessBeforeInitialization如下:

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(new PrivilegedAction<Object>() {
                public Object run() {
                    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(
                        new EmbeddedValueResolver(this.applicationContext.getBeanFactory()));
            }
            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);
            }
        }
    }

可以看出ApplicationContext利用ApplicationContextAwareProcessor完成了ApplicationContext中特有的一些Aware的调用,发生的时机在初bean始化之前。

一种特殊的BeanPostProcessor-InstantiationAwareBeanPostProcessor

前文提到BeanPostProcessor主要作用于Bean实例化后,初始化前后,但是存在特例,InstantiationAwareBeanPostProcessor就是特例,其发生在Bean实例化前,
在真正调用doCreate()创建bean实例化之前,调用了resolveBeforeInstantiation进行了短路操作,如果此方法返回值不为空则直接返回bean。spring注释“Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. ”给BeanPostProcessors一个机会返回代理proxy对象。

try {   
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.  
 Object bean = resolveBeforeInstantiation(beanName, mbd); 
  if (bean != null) {
      return bean;
   }
}



    protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
        Object bean = null;
        if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            // Make sure bean class is actually resolved at this point.
            if (mbd.hasBeanClass() && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                bean = applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName);
                if (bean != null) {
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
            mbd.beforeInstantiationResolved = (bean != null);
        }
        return bean;
    }

我们熟知的AOP,对target对象进行代理就是实现了InstantiationAwareBeanPostProcessor接口,在Bean实例化之前短路操作返回代理Proxy对象。

ApplicationContext的事件发布

--待续

总结

本文总结了Spring容器中几种使用较多的扩展机制,Spring作为一个设计良好的框架,遵循了“对修改封闭,对扩展开放”的原则,我们可以根据自己的实际需要来自定义BeanFactoryPostProcessor,BeanPostProcessor来在bean的生命周期里doSomething,实现各种Aware接口拿到容器中提供的一些有用对象,通过自定义监听器监听容器的事件等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值