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

我们都知道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://img2018.cnblogs.com/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://img2018.cnblogs.com/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请看我其他相关博客。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

偷偷学习被我发现

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值