您现在的位置是:首页 >技术教程 >一起学SF框架系列4.6-模块context-AbstractApplicationContext网站首页技术教程
一起学SF框架系列4.6-模块context-AbstractApplicationContext
org.springframework.context.ApplicationContext接口表示Spring IoC容器,负责实例化、配置和组装bean。容器通过读取配置元数据来获取关于实例化、配置和组装哪些对象的指令。配置元数据以XML、Java注释或Java代码表示。它允许您表达组成应用程序的对象以及这些对象之间丰富的相互依赖关系。AbstractApplicationContext是实现ApplicationContext接口的主体,是SF核心类之一,需仔细学习分析。
类作用
1、抽象实现ApplicationContext(应用容器)的通用功能,具体资源配置由子类实现。本类采用了Template Method design pattern(知识点:模板法设计模式),实现由子类完成。
2、可检测其内部bean工厂中定义自动注册的特殊bean,包括:org.springframework.beans.factory.config.BeanFactoryPostProcessor 、org.springframework.beans.factory.config.BeanPostProcessor 、org.springframework.context.ApplicationListener
3、提供org.springframework.context.MessageSource解析,包括委托给父容器解析。
4、提供applicationEventMultimaster支持事件播放。默认多播使用SimpleApplicationEventMulticast。
5、扩展实现资源加载DefaultResourceLoader。
从作用可见,这个类就是ApplicationContext的抽象实现。
类关系
类关系图如下:
有图可看出,主要实现ApplicationContext是该类。虽然是抽象类,但大部分工作在这里完成。
类实现
refresh() - 核心方法
refresh负责初始化spring容器,是应用的真正入口。之所以不是init,是因为容器初始化不是一次性行为,而是可以多次进行初始化,这样可以更好的适用复杂环境,也奠定了热更新的基础。
1、方法作用
1)加载或刷新的资源可能来自基于Java的配置、XML文件、属性文件、关系数据库模式或某种其他格式的配置。
2)作为一个启动方法,它应该销毁之前已经创建的singletons。如果失败,应避免资源悬空,即要么失败,要么所有Bean成功初始化。
3)如果bean工厂无法初始化,则跑异常BeansException。如果已初始化并多次刷新,抛 异常IllegalStateException
2、主体代码(#是分析注释)
public void refresh() throws BeansException, IllegalStateException {
//该方法在容器中需同步执行
synchronized (this.startupShutdownMonitor) {
//记录应用步骤-spring.context.refresh
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
//应用容器预处理
// Prepare this context for refreshing.
prepareRefresh();
//刷新内部beanFactory,加载BeanDefinition,调用后代类AbstractXmlApplicationContext.refreshBeanFactory()实现
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//BeanFactory容器预处理:配置属性
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
//至此,应用容器和beanFactory容器都准备好了
try {
//初始化BeanFactory的后处理:默认为空方法,如果需有特定的处理,继承重载postProcessBeanFactory方法即可
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
//记录应用步骤-spring.context.beans.post-process开始
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
//调用beanFactory的处理器注册bean
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
//注册Bean的后处理
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
//记录应用步骤-spring.context.beans.post-process步骤结束
beanPostProcess.end();
//初始化MessageSource(消息支持参数和国际化)
// Initialize message source for this context.
initMessageSource();
//初始化事件广播器
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
//在单例模式Bean初始化前初始化特殊bean,此处为空方法,在需要初始化特殊bean的子孙类中实现
// Initialize other special beans in specific context subclasses.
onRefresh();
//注册所有监听器bean和所有events
// Check for listener beans and register them.
registerListeners();
//实例化所有剩余的(非延迟初始化)单例bean
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
//最后一步:发布相关事件
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
//如果异常,销毁已初始化的单例对象避免资源悬置
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
contextRefresh.end();
}
}
}
该方法作为容器初始化核心入口,需逐一进行解析。
prepareRefresh()
方法作用:应用容器预处理。
protected void prepareRefresh() {
//设置容器状态为active
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
//打印日志(可显示进度)
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
//初始化属性资源(默认为空方法)
// Initialize any placeholder property sources in the context environment.
initPropertySources();
//校验所有需解析的属性
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
//刷新前监听器为空时,把之前的应用监听器放到刷新前监听器
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
//刷新前监听器不为空时,把刷新前的应用监听器放到当前应用监听器
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
//刷新前的应用事件清空
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
obtainFreshBeanFactory()
方法作用:创建BeanFactory;解析xml格式的bean配置,加载到BeanDefinitionReader。
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
该方法只是简单调用后代类AbstractRefreshableApplicationContext.refreshBeanFactory()实现。
prepareBeanFactory(beanFactory)
方法作用:配置BeanFactory容器属性。
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
//配置BeanFactory使用的类加载器java.lang.ClassLoader
beanFactory.setBeanClassLoader(getClassLoader());
//配置BeanFactory使用的表达式解析器StandardBeanExpressionResolver 注1
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//配置BeanFactory的Resource属性编辑器(propertyEditor)-StandardEnvironment()(getEnvironment()返回) 注2
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks. 注3
//配置BeanPostProcessor
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//Bean注入过程中,下面的类不需要自动装配
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
//BeanFactory本身可看作一个普通类,需把实现依赖注入用到的相关类同BeanFactory绑定
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
//注册一个BeanPostProcessor-ApplicationListenerDetector,用于检测不能用getBeanNamesForType检测到的Bean
// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
//加载LoadTimeWeaver 注4
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
//加载环境相关的Bean到beanFactory
// Register default environment beans.
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
}
注1、BeanFactory用到的Bean类表达式解析器由SpEL提供,标准表达式解析器就是StandardBeanExpressionResolver
注2、Bean属性编辑器(propertyEditor)指可对bean的属性进行设置管理的工具。
注3、Aware类基本性质都一样,详见https://blog.csdn.net/davidwkx/article/details/130790874
注4、实现AOP是通过织入方式实现,Java中存在三种织入方式:编译期织入、类加载期织入和运行期织入。SF使用AspectJ包实现AOP,默认织入方式为类加载期织入(LoadTimeWeaver )。另该处的NativeDetector.inNativeImage()指在Spring Native项目中应用可以打包为原生镜像的情况下不加载LoadTimeWeaver ,原生镜像运行时不需要JVM,没有类加载过程;LoadTimeWeaver只针对应用打包为JVM可执行文件时有效。
invokeBeanFactoryPostProcessors(beanFactory)
调用已注册到beanFactory的所有BeanPostProcessors处理器注册生成bean。
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//具体实现在PostProcessorRegistrationDelegate静态方法实现。
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
//下面代码实现实际在prepareBeanFactory(beanFactory)已实现,此处似乎多余
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors详见https://blog.csdn.net/davidwkx/article/details/130794306
registerBeanPostProcessors(beanFactory)
注册beanPostProcessors
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
PostProcessorRegistrationDelegate.registerBeanPostProcessors详见https://blog.csdn.net/davidwkx/article/details/130794306
initMessageSource()
初始化MessageSource(消息支持参数和国际化)
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource hms &&
hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
initApplicationEventMulticaster()
初始化事件广播器
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
registerListeners()
注册所有监听器bean和所有events。
protected void registerListeners() {
//先注册原有监听器
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
//注册监听器bean
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
//加入还存在的前期事件
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
finishBeanFactoryInitialization(beanFactory)
实例化所有剩余的(非延迟初始化)单例bean
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
//初始化类型转换服务
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
//注册值解析器(主要针对@Value类注解)
// Register a default embedded value resolver if no BeanFactoryPostProcessor
// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
//lambda表达式
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
//先初始化加载植入类
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
//不使用特殊加载类,用标准的类加载器
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
//bean初始化前,所有的bean定义不应该再发生变化
// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();
//初始化单实例类(非延迟加载的) 注1
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
注1:preInstantiateSingletons实现在org.springframework.beans.factory.support.DefaultListableBeanFactory。