Spring源码深度解析(八)——Spring环境的准备化工作

准备就包括了prepareRefresh(),obtainFreshBeanFactory()和prepareBeanFactory(beanFactory)。下面就逐个向下分析

prepareRefresh()

主要是对容器的激活标记的设置,启动时间,验证环境还有初始化一个用于对消息事件的提前发布的Set,代码及其注释如下

/**
	 * Prepare this context for refreshing, setting its startup date and
	 * active flag as well as performing any initialization of property sources.
	 */
	protected void prepareRefresh() {
		// 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()

这个是获取在AnnotationContextApplicationContext中传入的BeanFactory,默认是DefaultListableBeanFactory。
可以从调试信息看到结果
在这里插入图片描述

prepareBeanFactory(beanFactory)

在上面得到BeanFactory后,现在就要对BeanFactory进行一些必要的设置以保证BeanFactory能正常运行,比如类加载器,Bean表达式解析器,Property资源编辑器,ApplicationContext的Bean后置处理器(可以对ApplicationContext进行扩展的),还有对一些内部接口类型的忽略,还有对一些的替换和对系统默认环境的注册。
代码如下

/**
	 * 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.
		//告诉内部bean工厂使用上下文类加载器
		beanFactory.setBeanClassLoader(getClassLoader());
		//添加bean的表达式解析器,使beanFactory可以识别bean表达式
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		//添加property资源编辑器注册器
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
		// Configure the bean factory with context callbacks.
		//添加Spring  bean的后置处理器   ApplicationContext的后置处理器
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));


		//一个类实现下面这些接口的时候不会被自动注入
		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 interface not registered as resolvable type in a plain factory.
		// MessageSource registered (and found for autowiring) as a bean.
		//如beanFactory这些类没有在工厂中,在此进行注册    依赖替换,如果需要BeanFactory就把beanFactory作为替换
		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

		// Register early post-processor for detecting inner beans as ApplicationListeners.
		// 注册事件监听器    如果这个Bean是ApplicationListener的子类,将它添加到listener列表
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

		// Detect a LoadTimeWeaver and prepare for weaving, if found.
		//加载时织入(不同于AOP这是静态的)
		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.
		//如果自定义的Bean中没有名字为“systemProperties”和“systemEnvironment”的Bean
		//key为“systemProperties”和“systemEnvironment”  value为存系统信息和系统环境配置的Map
		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());
		}
	}

可以看到准备完成的BeanFactory
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值