目录
Spring IOC源码步骤分析
第一步: 检查并设置Spring XML配置文件
功能:设置此应用程序上下文的配置文件位置,如果未设置;Spring可以根据需要使用默认值
setConfigLocations(configLocations);
在Main方法Debug启动进入断点,按F7跟进入其方法查看,会进入
ClassPathXmlApplicationContext类的构造方法中public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext { private Resource[] configResources; // 如果已经有 ApplicationContext 并需要配置成父子关系,那么调用这个构造方法 public ClassPathXmlApplicationContext(ApplicationContext parent) { super(parent); } ... public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException { super(parent); // 根据提供的路径,处理成配置文件数组(以分号、逗号、空格、tab、换行符分割) setConfigLocations(configLocations); if (refresh) { refresh(); // 核心方法 剩余的所有步骤都在此方法中!!! } } ... }首先执行
"设置配置位置setConfigLocations"的方法,解析SpringXML配置文件地址存储到configLocations属性中。public void setConfigLocations(@Nullable String... locations) { //判断配置路径是否为null if (locations != null) { Assert.noNullElements(locations, "Config locations must not be null"); //循环将配置文件路径存储到属性configLocations中 this.configLocations = new String[locations.length]; for (int i = 0; i < locations.length; i++) { this.configLocations[i] = resolvePath(locations[i]).trim(); } } else { this.configLocations = null; } }
第二步:执行创建Bean容器之前的准备工作
注意:除了第一步设置XML配置文件路径,剩余的步骤都在该类的refresh();这个方法中执行,所以我们需要Debug跟进入这个方法

refresh();方法如下所示;因为整个SpringApplication的构建都在这个方法 里面所以就现在这里展现一下和大家混个脸熟.
public void refresh() throws BeansException, IllegalStateException { //对下面的代码块添加同步锁 synchronized (this.startupShutdownMonitor) { //第二步: 执行创建容器前的准备工作 :记录下容器的启动时间、标记“已启动”状态、处理配置文件中的占位符 prepareRefresh(); //第三步:创建Bean容器,加载XML配置信息 : 如果存在容器进行销毁旧容器,创建新容器,解析XML配置文件为一个个BeanDefinition定义注册到新容器(BeanFactory)中,注意Bean未初始化 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //第四步: 设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean prepareBeanFactory(beanFactory); try { //第五步:加载并执行后置处理器 postProcessBeanFactory(beanFactory); //执行postProcessBeanFactory()方法 invokeBeanFactoryPostProcessors(beanFactory); // 实例化拦截Bean创建的后置处理器beanPostProcessors registerBeanPostProcessors(beanFactory); //第六步: 初始化Spring容器的消息源 initMessageSource();
