Spring容器刷新—02—obtainFreshBeanFactory

这次的内容是上图中的第2步,大概内容就是创建一个 BeanFactory 的实例。

BeanFactory和ApplicationContext

你要是看 spring 源码会发现 BeanFactory 的实现类相当多,而且还有各种子接口以及子接口的实现类。

ApplicationContextBeanFactory,但是你不能说 BeanFactoryApplicationContext

ApplicationContext 实现了 BeanFactory 的同时增强了 BeanFactory,所谓的增强大体上指的是上图中 ApplicationContext 实现的除了 BeanFactory 接口之外的其他接口的功能。

本文仅仅列出常用的两类实现。如下图所示:

那么这么多的实现类,实际应用中到底实例化的是哪个?

这个问题嘛…… 看情况……

上图列出来两大类实现:

  • xml 版的实现: 大体上指的是(不是绝对) AbstractRefreshableApplicationContext 的子类
    • 也就是当年我们哼哧哼哧集成 springservlet 那个年代的事情
    • 大多数不就是 ClassPathXmlApplicationContext 吗?(略过)
  • 注解版 的实现: 大体上指的是(不是绝对) GenericApplicationContext 的子类
    • Webflux 环境下一般是 AnnotationConfigReactiveWebServerApplicationContext
    • Servlet 环境下一般是 AnnotationConfigServletWebServerApplicationContext

这里提到的实现类,无论是哪个,都是派生自 AbstractApplicationContext 的。他们都是 BeanFactory

既然有 N 个 BeanFactory 的实现类,那么我们应用程序中到底使用的是哪一个呢? 文章末尾再说,先把我们本期的重点 obtainFreshBeanFactory() 的逻辑介绍完。

obtainFreshBeanFactory

obtainFreshBeanFactory() 的工作就是在刷新之前搞到一个 热乎的 BeanFactory 实例,涉及到的两个方法都是由子类实现的。

  • refreshBeanFactory(): 刷新 BeanFactory,由不同的子类提供各自的实现。
  • getBeanFactory(): 返回当前 ApplicationContext 中创建好的 BeanFactory,简单的实现往往就是一个 getter 方法。
public abstract class AbstractApplicationContext extends DefaultResourceLoader
        implements ConfigurableApplicationContext {
    /**
     * Tell the subclass to refresh the internal bean factory.
     * @return the fresh BeanFactory instance
     * @see #refreshBeanFactory()
     * @see #getBeanFactory()
     */
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        refreshBeanFactory();
        return getBeanFactory();
    }

    /**
     * Subclasses must implement this method to perform the actual configuration load.
     * The method is invoked by {@link #refresh()} before any other initialization work.
     * <p>A subclass will either create a new bean factory and hold a reference to it,
     * or return a single BeanFactory instance that it holds. In the latter case, it will
     * usually throw an IllegalStateException if refreshing the context more than once.
     * @throws BeansException if initialization of the bean factory failed
     * @throws IllegalStateException if already initialized and multiple refresh
     * attempts are not supported
     */
    protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;


    /**
     * Subclasses must return their internal bean factory here. They should 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值