8-Spring源码解析之refresh(2)——【prepareRefresh】与【ConfigurableListableBeanFactory】

本文深入探讨Spring的refresh方法中的prepareRefresh步骤,重点解析BeanFactory的获取与配置文件的处理。文章介绍了如何通过包扫描获取BeanFactory,特别是ConfigurableListableBeanFactory,它扩展了基本功能,能解析所有Spring配置文件中的bean。通过loadBeanDefinition读取XML配置文件,将bean定义加载到beanDefinitionMap中。同时,文章也讨论了内部结构和调用关系,帮助理解Spring容器的工作原理。
摘要由CSDN通过智能技术生成

上一篇:Spring源码解析之refresh(1)——概览

上一篇介绍了refresh方法的概览,其中包含12个方法,接下来我们就依照顺序依次聊一下每个方法所实现的功能以及如何实现的。这篇文章先介绍【prepareRefresh】与【ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()】。

<spring.version>4.3.9.RELEASE</spring.version>

1. prepareRefresh方法

	protected void prepareRefresh() {
   
		// 记录容器启动的事件.
		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());
			}
		}

		// 扩展方法:
		initPropertySources();

		// Validate that all properties marked as required are resolvable:
		// see ConfigurablePropertyResolver#setRequiredProperties
		// 这里我没有用到,所以暂时也没有具体看是做什么的,后续再补充吧!
		getEnvironment().validateRequiredProperties();

		// Allow for the collection of early ApplicationEvents,
		// to be published once the multicaster is available...
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}
1.1 AbstractRefreshableWebApplicationContext#initPropertySources
	protected void initPropertySources() {
   
		ConfigurableEnvironment env = getEnvironment();
		if (env instanceof ConfigurableWebEnvironment) {
   
			((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
		}
	}

在这里插入图片描述
在类AbstractApplicationContext中该方法是空实现,而因为该工程是MVC工程,因此这里面使用的是调用其子类AbstractRefreshableApplicationContext中的方法实现的。(待补充mvc相关知识。)

2. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()

这个方法很重要,从字面上理解是获取BeanFactory。以包扫描的方式使用Spring时,走到该方法的类是:AbstractApplicationContext,从下面的图中可以看出,AbstractApplicationContext实现了BeanFacotory接口。因此它不但包含BeanFacotory接口的所有功能,还在其基础上增加了大量的扩展应用。

在这里插入图片描述
在这里插入图片描述

经过方法obtainFreshBeanFactory() 之后,ApplicationContext就拥有了BeanFactory的全部功能。

实际上该方法的主要功能是:会解析所有Spring的配置文件,这些配置文件我们一般都放在 resources目录下面。 将所有的配置文件中的bean都转换为BeanDefinition
我们有2种方式获取bean信息,方式一:通过配置文件的<bean>。方式二:通过配置文件的扫描包的形式。<context:component-scan base-package="com.huanjie"></context:component-scan>

执行完该方法后,主要关注以下两个变量中的值

  • beanDefinitionName
    • 存储beanFactory中的所有beanbeanName
  • beanDefinitionMap
    • 存储beanFactory中的所有bean<beanName, beanDefinition>
	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
   
		// --- 【1】 --- 
		
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值