ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Spring加载流程源码分析____ClassPathXmlApplicationContext源码跟踪(简捷版)

2019-07-13 21:06:27  阅读:247  来源: 互联网

标签:xml 初始化 parent BeanFactory Spring refresh ____ 源码 ApplicationContext


我们都知道BeanFactory是Spring的核心相当于心脏,而ApplicationContext相当于spring的完整躯干,我们从源码上:

BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationcontext.xml"));
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");


ApplicationContext继承了BeanFactory,ResourceLoader提供了类的管理以及资源的加载,同时又继承了EnvironmentCapable(环境),MessageSource(消息), ApplicationEventPublisher(事件)等统一管理,真是的算上一个完整的躯干了。
[外链图片转存失败(img-5nWAdrFj-1563022126423)(https://www.icode9.com/i/l/?n=18&i=blog/1611808/201907/1611808-20190704142748167-1388529892.png)]

ApplicationContext相比较于BeanFactory,扩展了很多功能,ApplicationContext继承了BeanFactory, 所以说ApplicationContext包含了BeanFactory所有功能。

ApplicationContext ac = new ClassPathXmlApplicationContext(“applicationcontext.xml”);

使用ClassPathXmlApplicationContext加载配置xml文件applicationcontext.xml,
我们追踪ClassPathXmlApplicationContext源码:
这里的String configLocation是applicationcontext.xml配置文件路径。

这里我们记住参数:configLocation是applicationcontext.xml,refresh是true,而parent是null;
super(parent)//1.初始化父类
setConfigLocations(configLocations);// 2.设置本地的配置信息
// 3.完成Spring容器的初始化
if (refresh) {
refresh();
}

1、super(parent)调用AbstractApplicationContext的构造函数,在AbstractApplicationContext中会初始化resourcePatternResolver。

这里一直跟踪super(parent)到底:
其实一直跟踪会发现都是super(parent)调用类的构造来初始化父类
在图片里此构造方法中就没有再显示的super(parent)了。
在this()方法里,也就是图片上的构造方法,在该构造方法对resourcePatternResolver 变量赋值。resourcePatternResolver 的作用是根据路径得到类的Resource对象;

查看getResourcePatternResolver方法:

创建PathMatchingResourcePatternResolver对象的时候,AbstractApplicationContext将自身作为ResourceLoader传递给了PathMatchingResourcePatternResolver;

那么好了,这里的parent是null;就直接可以看出来AbstractApplicationContext中设置父类的参数parent为null,setParent(null);初始化了this();也就初始化了resourcePatternResolver。

因为parent为null所以if语句中的代码不会执行,所以此if中的代码在此逻辑中不会执行,所以在此就没有分析的必要了。
初始化的第一部分就分析完毕了,这部分的主要工作是为后续Resource处理准备好处理类。

2、setConfigLocations(configLocations)解析spring的配置文件地址,设置到configLocations。
这里的configLocations就是配置文件的路径。

this.configLocations[i] = resolvePath(locations[i]).trim();//循环取出每一个path参数,在此处就一个“applicationContext.xml”

  1. setConfigLocations主要工作有两个:创建环境对象ConfigurableEnvironment 、处理ClassPathXmlApplicationContext传入的字符串中的占位符;
  2. 环境对象ConfigurableEnvironment中包含了当前JVM的profile配置信息、环境变量、 Java进程变量;
  3. 处理占位符的关键是ConfigurableEnvironment、PropertyResolver、PropertyPlaceholderHelper之间的配合

分别针对上面3点看看源码:
// 这个方法的目的是替换掉path字符串中的占位符${XXX}这样的内容,

进入getEnvironment(),创建环境对象ConfigurableEnvironment

环境对象ConfigurableEnvironment中包含了当前JVM的profile配置信息、环境变量、 Java进程变量;

进入resolveRequiredPlaceholders方法,处理ClassPathXmlApplicationContext传入的字符串中的占位符
[外链图片转存失败(img-Qlr9nw6E-1563022126446)(https://www.icode9.com/i/l/?n=18&i=blog/1611808/201907/1611808-20190704155227809-1581305364.png)]

3、refresh()这是ApplicationContext初始化的核心,会在这里初始化BeanFactory,解析XML加载BeanDefinition,注册bean处理器,注册事件添加监听等。
这里if判断refresh为true。

这里的refresh源码太多了,我就把源码复制下来:

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

            // 初始化BeanFactory,进行xml文件读取,这里是重点
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // 对BeanFactory进行各种功能的填充
            prepareBeanFactory(beanFactory);

            try {
                // 子类覆盖方法做其他的处理
                postProcessBeanFactory(beanFactory);

                // 激活BeanFactory的处理器
                invokeBeanFactoryPostProcessors(beanFactory);

                // 注册拦截Bean创建的Bean处理器
                registerBeanPostProcessors(beanFactory);

                // 为上下文初始化Message源
                initMessageSource();

                // 初始化应用消息广播器
                initApplicationEventMulticaster();

                // 留给子类初始化其他的bean
                onRefresh();

                // 查找Listeners bean,注册到消息广播器中
                registerListeners();

                // 初始化剩下的单实例
                finishBeanFactoryInitialization(beanFactory);

                // 完成刷新过程,通知生命周期处理器
                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();
            }
        }
    }

查看ConfigurableListableBeanFactory可以看到XmlBeanFactory,这里我们就可以知道初始化了
BeanFactory。
















接下就是对XML配置文件的解析了,具体如何解析XML请看我其他相关博客。

标签:xml,初始化,parent,BeanFactory,Spring,refresh,____,源码,ApplicationContext
来源: https://blog.csdn.net/qq_37432174/article/details/95790984

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有