BeanFactory vs ApplicationContext
相同点
都是spring的容器接口,都具备基本的容器功能, ApplicationContext本质上也是BeanFactory,它是BeanFactory的子接口。
不同点
BeanFactory只具备基本的容器功能,适用于性能受限的特殊场景。
ApplicationContext是高级容器,在BeanFactory的基础上做了增强,如:
- 支持i18n
- 支持ResourceLoader,能作为抽象资源的访问接口
- 消息发送机制(ApplicationEvent)
- 默认初始化Bean
- 智能支持BeanFactoryPostProcessor ,BeanPostProcessor以及其他特殊类型bean的自动识别
ApplicationContext接口
源码如下:
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
/**
* Return the unique id of this application context.
* @return the unique id of the context, or {@code null} if none
*/
@Nullable
String getId();
/**
* Return a name for the deployed application that this context belongs to.
* @return a name for the deployed application, or the empty String by default
*/
String getApplicationName();
/**
* Return a friendly name for this context.
* @return a display name for this context (never {@code null})
*/
String getDisplayName();
/**
* Return the timestamp when this context was first loaded.
* @return the timestamp (ms) when this context was first loaded
*/
long getStartupDate();
/**
* Return the parent context, or {@code null} if there is no parent
* and this is the root of the context hierarchy.
* @return the parent context, or {@code null} if there is no parent
*/
@Nullable
ApplicationContext getParent();
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
}
可以看出Application实现了几个关键接口:
-
EnvironmentCapable
持有Environment实例,Environment在持有配置属性方面至关重要。 -
ListableBeanFactory
ListableBeanFactory提供了迭代容器中bean的功能 -
HierarchicalBeanFactory
HierarchicalBeanFactory表示容器有层级,可以设置和获取父容器 -
MessageSource
使得容器支持i18n属性文件配置获取和参数化配置读取
Spring提供了三种MessageSource:
StaticMessageSource
ResourceBundleMessageSource
ReloadableResourceBundleMessageSource -
ApplicationEventPublisher
说明容器担当了事件发布者的角色。默认提供的事件类型有:
1)ContextRefreshedEvent:容器在初始化或刷新后触发的事件类型
2)ContextClosedEvent:容器在即将关闭时发布的事件类型
3)RequestHandledEvent: web请求后发布的事件自定义ApplicationListener, 实现ApplicationListener接口。
-
ResourcePatternResolver
ResourcePatternResolver是ResourceLoader的子接口,说明容器本身是ResourceLoader
的实例,可作为通用资源访问的实例。
常见ApplicationContext容器
在传统xml配置bean的时代(spring 3以前),web项目最常用的是XmlWebApplicationContext,从java config之后,特别是spring boot大量应用,最常用的是AnnotationConfigApplicationContext。这两个ApplicationContext我们接下来都会进行分析。
其他不太常用的还有:ClasspathXmlApplicationContext, FileSystemXmlApplicationContext等。
小结
本章介绍了ApplicationContext接口,比较了跟BeanFactory的异同点,然后看了ApplicationContext接口的定义,以及分析了常见的ApplicationContext有哪些。下一章重点分析XmlWebApplicationContext。