spring源码-bean之增强初始化-3

  一、ApplicationContext的中文意思是“应用上下文”,它继承自BeanFactory接口,除了包含BeanFactory的所有功能之外,在国际化支持、资源访问(如URL和文件)、事件传播等方面进行了良好的支持,被推荐为Java EE应用之首选,可应用在Java APP与Java Web中。

  二、ApplicationContext相对于XmlBeanFactory做了很多是拓展的功能,而这些拓展的功能,不管是在容器初始化,还是中间需要处理的过程,都做了很大的改善以及深入。

  三、先看一下ApplicationContext的继承关系图,了解一下和XmlBeanFactory的区别

  注意:这是一张ClassPathXmlApplicationContext的继承关系图,目前是为了更好的呈现,当前bean在加载的时候做的那些事情。

  四、可能有人会问,为什么没有DefaultListableBeanFactory的相关属性了呢,这个在源码的讲解部分会细说。

  五、源码解析

  1)增强性的bean容器初始化实现方式

     public static void main(String[] args) {
        //增强性的bean容器初始化化
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-bean.xml");
    }

  2)实现过程

    public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
        this(new String[]{configLocation}, true, (ApplicationContext)null);
    }

    public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
        super(parent);
        //设置需要加载的xml文件
        this.setConfigLocations(configLocations);
        if (refresh) {
            //容器的整个初始化过程都在这里实现
            this.refresh();
        }

    }

  3)refresh

    public void refresh() throws BeansException, IllegalStateException {
        Object var1 = this.startupShutdownMonitor;
        synchronized(this.startupShutdownMonitor) {
            //前期准备工作
            this.prepareRefresh();
            //xml解析过程
            ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
            //beanFactory的准备过程
            this.prepareBeanFactory(beanFactory);

            try {
                //BeanFactoryPostProcessor接口拓展
                this.postProcessBeanFactory(beanFactory);
                this.invokeBeanFactoryPostProcessors(beanFactory);
                //注册BeanPostProcessor的实现接口,实际调用在getBean的时候
                this.registerBeanPostProcessors(beanFactory);
                //国际化
                this.initMessageSource();
                //初始化应用广播器
                this.initApplicationEventMulticaster();
                //子类应用
                this.onRefresh();
                //监听部分
                this.registerListeners();
                //完成初始化
                this.finishBeanFactoryInitialization(beanFactory);
                //完成刷新
                this.finishRefresh();
            } catch (BeansException var4) {
                this.destroyBeans();
                this.cancelRefresh(var4);
                throw var4;
            }
        }
    }

  六、因为ApplicationContext在做容器初始化的时候做了很多工作,所以我这里会形成一个目录,来讲解剩下的部分。

  1)spring源码-增强容器xml解析-3.1

  2)spring源码-BeanFactoryPostProcessor-3.2

  3)spring源码-BeanPostProcessor-3.3

  4)spring源码-Aware-3.4

  5)spring源码-国际化-3.5

  6)spring源码-事件&监听3.6

 

posted @ 2018-08-17 14:27  小不点丶  阅读(980)  评论(0编辑  收藏  举报