专栏首页浪人聊编程AbstractApplicationContext源码分析

AbstractApplicationContext源码分析

一 refresh源码分析

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
                        //准备刷新上下文环境
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
                        //初始化beanfactory,并进行xml文件读取
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
                        //对BeanFactory进行各种功能填充
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
                                //子类覆盖方法做额外处理
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
                                //激活各种BeanFactory处理器
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
                                //注册BeanBeanPostProcessor
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
                                //为上下文初始化message源,即不同语言的消息体,国际化处理.
				initMessageSource();

				// Initialize event multicaster for this context.
                                //初始化应用消息广播器
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
                                //留给子类初始化其他bean
				onRefresh();

				// Check for listener beans and register them.
                                //在所有注册的bean中查找Listener bean,注册到消息广播器中
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
                                //初始化剩下的单利bean(非惰性)
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
                               //完成刷新,通知生命周期处理器,同时发出ContextRefreshEvent 通知别人
				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();
			}
		}
	}

二 prepareBeanFactory 方法源码分析

	/**
	 * Configure the factory's standard context characteristics,
	 * such as the context's ClassLoader and post-processors.
	 * @param beanFactory the BeanFactory to configure
	 */
	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
                //设置beanFactory的classloader为当前context的classLoader
		beanFactory.setBeanClassLoader(getClassLoader());
                //设置beanFactory的表达式语言处理器,spring3增加了表达式语言的支持
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
                //为beanfactory增加了一个默认的propertyEditor,这个主要针对bean的属性等设置管理的一个工具
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
                //添加BeanPostProcessor
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
                //设置需要忽略自动配置接口
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
		beanFactory.ignoreDependencyInterface(EnvironmentAware.class);

		// 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);

		// Detect a LoadTimeWeaver and prepare for weaving, if found.
		if (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()));
		}

		// 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());
		}
	}

我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=2okgifrej9uss

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • PostProcessorRegistrationDelegate 源码分析 原

    PostProcessorRegistrationDelegate 是一个静态工具类,包访问权限,AbstractApplicationContext's po...

    东营浪人
  • maven多环境配置文件

    东营浪人
  • BeanDefinitionParserDelegate 分析

    东营浪人
  • Spring源码学习笔记(3)——容器的功能扩展

    张申傲
  • Spring学习之浅析refresh()执行逻辑

    对于AbstractApplicationContex#refresh()方法逻辑,可所谓是贯通spring框架核心逻辑,溪源在debug过程中,理解起来...

    沁溪源
  • 深入理解Spring系列之四:BeanDefinition装载前奏曲

    框架的源码分析,有些代码可以暂时忽略,如Spring如何进行XML模式校验的、XML解析的细节等,这些代码可以在了解了整体的原理之后,再做针对性的分析,关注重点...

    JavaQ
  • 极客周刊丨谷歌最强AI助手,余额宝不限购回归,传销组织云联惠被查封...

    一川水巷
  • Spring扩展点之BeanFactoryPostProcessor

    BeanFactoryPostProcessor接口是Spring中一个非常重要的接口,它的接口定义如下

    Java学习录
  • 万能的BeanPostProcessor是如何让spring无限扩展的?

    很多朋友一提到spring,首先想到的肯定是IOC(控制反转)和 AOP (面向切面编程),没错,这两个是spring的核心功能。但是什么技术让spring拥...

    苏三说技术
  • Clojure 学习入门(15)—— 条件判断

    一、标准的流程控制 if:  将一个判断表达式作为它的第一个参数进行求值。如果求值为true,那么就返回它的第二个参数(相当于“then”子句)的求值结果。如...

    阳光岛主

扫码关注云+社区

领取腾讯云代金券