上一篇博文介绍了Spring有三个核心组件,分别是Bean组件,Context组件和Core组件,这一篇详细介绍每个组件。
Bean组件
Bean组件对Spring非常重要。Bean组件在Spring的org.springframework.beans包下。这个包下的所有类主要解决了三件事:Bean的定义,Bean的创建以及对Bean的解析。对Spring的使用者来说唯一需要关心的就是Bean的创建,其他两个由Spring在内部帮你完成了,对你来说是透明的。
Spring Bean的创建是典型的工厂模式,它的顶级接口是BeanFactory。下图是Bean工厂的继承关系:
Context组件
Context组件在Spring的org.springframework.context包下,Context实际上就是给Spring提供了一个运行时的环境,用以保存各个对象的状态。
ApplicationContext是Context的顶级父类,他除了能标识一个应用环境的基本信息外,他还继承了五个接口,这五个接口主要是扩展了Context的功能。下面是Context的类结构图:
从上图中可以看出 ApplicationContext 继承了 BeanFactory,这也说明了 Spring 容器中运行的主体对象是 Bean,另外 ApplicationContext 继承了 ResourceLoader 接口,使得 ApplicationContext 可以访问到任何外部资源,这将在 Core 中详细说明。
总体来说ApplicationContext必须要完成以下几件事:
- 标识一个应用环境
- 利用BeanFactory创建Bean对象
- 保存对象关系表
- 能够捕获各种事件
Context作为Spring的IOC容器,基本上整合了Spring的大部分功能,或者说是大部分功能的基础。
Core组件
Core 组件作为 Spring 的核心组件,他其中包含了很多的关键类,其中一个重要组成部分就是定义了资源的访问方式。这种把所有资源都抽象成一个接口的方式很值得在以后的设计中拿来学习。
IOC容器如何工作
IOC容器实际上就是Context组件结合其他两个组件共同构建了一个Bean关系网, 如何构建这个关系网?构建的入口就在AbstractApplicationContext 类的refresh方法中。这个方法的代码如下:
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;
}
}
}
这个方法就是构建整个 Ioc 容器过程的完整的代码,了解了里面的每一行代码基本上就了解大部分 Spring 的原理和功能了。
这段代码主要包含了这样几个步骤:
- 构建BeanFactory,以便于产生所需的“演员”
- 注册可能感兴趣的事件
- 创建Bean实例对象
- 触发被监听的事件