这次的内容是上图中的第2步,大概内容就是创建一个 BeanFactory
的实例。
BeanFactory和ApplicationContext
你要是看 spring 源码会发现 BeanFactory
的实现类相当多,而且还有各种子接口以及子接口的实现类。
ApplicationContext
是 BeanFactory
,但是你不能说 BeanFactory
是 ApplicationContext
。
ApplicationContext
实现了 BeanFactory
的同时增强了 BeanFactory
,所谓的增强大体上指的是上图中 ApplicationContext
实现的除了 BeanFactory
接口之外的其他接口的功能。
本文仅仅列出常用的两类实现。如下图所示:
那么这么多的实现类,实际应用中到底实例化的是哪个?
这个问题嘛…… 看情况……
上图列出来两大类实现:
xml
版的实现: 大体上指的是(不是绝对)AbstractRefreshableApplicationContext
的子类- 也就是当年我们哼哧哼哧集成
spring
和servlet
那个年代的事情 - 大多数不就是
ClassPathXmlApplicationContext
吗?(略过)
- 也就是当年我们哼哧哼哧集成
- 注解版 的实现: 大体上指的是(不是绝对)
GenericApplicationContext
的子类- Webflux 环境下一般是
AnnotationConfigReactiveWebServerApplicationContext
- Servlet 环境下一般是
AnnotationConfigServletWebServerApplicationContext
- Webflux 环境下一般是
这里提到的实现类,无论是哪个,都是派生自 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