SpringIOC--初始化源码解析

来源:互联网 发布:sql语句基本查询 编辑:程序博客网 时间:2024/05/19 19:42

  • IOC容器的初始化过程
    • 步骤
    • 第一步Resource定位过程

    在上一篇 Spring从入门到精通(一)—-IoC(控制反转) 中,详细的介绍了IOC的基本原理,本篇博客就不再赘述;这次主要是从源码的角度来给大家分享SpringIOC的初始化过程。深入的了解其原理。

    SpringIOC容器的关键两个主要的容器系列:

这里写图片描述
    BeanFactory提供一些最基础的功能,我们以水桶为例,如果把IOC看成一个水桶的话,那么这个BeanFactory就定义了可以作为水桶的最基本的功能:能装水或者有个提手什么的。这个水桶除了满足基本的功能外,为了不同场合,不同用户的需求,生产厂家还要提供更为丰富的功能,大众型的、中等型的、豪华型的等,这些就需要用到ApplicationContextApplicationContext应用上下文是建立在BeanFactory之上的。下图是IOC容器中的主要接口的设计:

这里写图片描述

IOC容器的初始化过程


步骤

    写了段简单的代码,IOC容器的具体的过程都在这一句话上(后台很硬的~_~):

BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");

    下面咱们就来看看IOC的后台是多么的硬,加了断点调试了下,跳进去的第一步是:

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)            throws BeansException {        super(parent);        setConfigLocations(configLocations);        if (refresh) {            //入口            refresh();        }    }

    上面代码的refresh()是IOC容器启动的入口,后边会牵扯一系列的复杂操作,看一下refresh的代码:

    @Override    public void refresh() throws BeansException, IllegalStateException {        synchronized (this.startupShutdownMonitor) {            // //调用容器准备刷新的方法,获取容器的当时时间,同时给容器设置同步标识              prepareRefresh();            // 在子类中启动refreshBeanFactory()的地方            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();            // 创建BeanFactory            prepareBeanFactory(beanFactory);            try {                // 设置BeanFactory的后置处理                postProcessBeanFactory(beanFactory);                // 调用BeanFactory的后处理器,这些后处理器是在Bean定义中向容器注册的                invokeBeanFactoryPostProcessors(beanFactory);                // 注册Bean的后处理器,在Bean常见过程中调用。                registerBeanPostProcessors(beanFactory);                // 对上下文中的消息源进行初始化                initMessageSource();                // 初始化上下文中的事件机制                initApplicationEventMulticaster();                // 初始化其他的特殊Bean                onRefresh();                // 检查监听Bean并且将这些Bean想容器注册                registerListeners();                // 实例化所有的(non-laze-init)单件                finishBeanFactoryInitialization(beanFactory);                //帆布容器事件,结束Refresh过程                finishRefresh();            }            catch (BeansException ex) {                if (logger.isWarnEnabled()) {                    logger.warn("Exception encountered during context initialization - " +                            "cancelling refresh attempt: " + ex);                }                // 为防止Bean资源占用,在异常处理中,销毁已经在前面过程中生成的单件Bean                destroyBeans();                // 重置‘active’标志                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();            }        }    }

    具体的来说:IOC容器的正式启动包括:BeanDefinition的Resouce定位,载入和注册三个基本过程。下面咱们就一步步的来看

第一步:Resource定位过程

  • refreshBeanFactory()
    代码量很大,咱们捡着关键点说,一个关键点就是refreshBeanFactory(),看一下具体的代码:
 protected final void refreshBeanFactory() throws BeansException {          if (hasBeanFactory()) {//如果已经有容器,销毁容器中的bean,关闭容器              destroyBeans();              closeBeanFactory();          }          try {               //创建IoC容器               DefaultListableBeanFactory beanFactory = createBeanFactory();               beanFactory.setSerializationId(getId());              //对IoC容器进行定制化,如设置启动参数,开启注解的自动装配等              customizeBeanFactory(beanFactory);              //调用载入Bean定义的方法,主要这里又使用了一个委派模式,在当前类中只定义了抽象的loadBeanDefinitions方法,具体的实现调用子类容器              loadBeanDefinitions(beanFactory);              synchronized (this.beanFactoryMonitor) {                  this.beanFactory = beanFactory;              }          }          catch (IOException ex) {              throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);          }      }

    refreshBeanFactory()方法的功能就是判断是否已经建立了BeanFactory,如果存在,则销毁并关闭该BeanFactory,然后再创建一个新的IOC容器来使用,这样来保证我们用的BeanFactory是最新的。保证我们要用到的水桶是最新的。

  • loadBeanDefinitions(beanFactory)
    新的BeanFactory创建好了,接下来就是调用loadBeanDefinitions(beanFactory)来装载Bean,要想装载Bean首先肯定是要先找到Bean的位置对吧,就好比你用桶装水,肯定你得先找到水源才行。
//Xml Bean读取器加载Bean定义资源  19    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {  20        //获取Bean定义资源的定位  21        Resource[] configResources = getConfigResources();  22        if (configResources != null) {  23            //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位  24            //的Bean定义资源  25            reader.loadBeanDefinitions(configResources);  26        }  27        //如果子类中获取的Bean定义资源定位为空,则获取FileSystemXmlApplicationContext构造方法中setConfigLocations方法设置的资源 ,这一步就会读取我们自己配的ApplicationContext.xml文件,在前面的setConfigLocations方法中已经设置28        String[] configLocations = getConfigLocations();  29        if (configLocations != null) {  30            //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位  31            //的Bean定义资源  32            reader.loadBeanDefinitions(configLocations);  33        }  34    }  
//重载方法,调用下面的loadBeanDefinitions(String, Set<Resource>);方法     public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {         return loadBeanDefinitions(location, null);     }     public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {         //获取在IoC容器初始化过程中设置的资源加载器         ResourceLoader resourceLoader = getResourceLoader();         if (resourceLoader == null) {             throw new BeanDefinitionStoreException(                     "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");         }         if (resourceLoader instanceof ResourcePatternResolver) {             try {                 //将指定位置的Bean定义资源文件解析为Spring IoC容器封装的资源                 //加载多个指定位置的Bean定义资源文件                 Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);                 //委派调用其子类XmlBeanDefinitionReader的方法,实现加载功能                 int loadCount = loadBeanDefinitions(resources);                 if (actualResources != null) {                     for (Resource resource : resources) {                         actualResources.add(resource);                     }                 }                 if (logger.isDebugEnabled()) {                     logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");                 }                 return loadCount;             }             catch (IOException ex) {                 throw new BeanDefinitionStoreException(                         "Could not resolve bean definition resource pattern [" + location + "]", ex);             }         }         else {             //将指定位置的Bean定义资源文件解析为Spring IoC容器封装的资源             //加载单个指定位置的Bean定义资源文件             Resource resource = resourceLoader.getResource(location);             //委派调用其子类XmlBeanDefinitionReader的方法,实现加载功能             int loadCount = loadBeanDefinitions(resource);             if (actualResources != null) {                 actualResources.add(resource);             }             if (logger.isDebugEnabled()) {                 logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");             }             return loadCount;         }     } 

    下面就是具体的对资源的定位

//获取Resource的具体实现方法     public Resource getResource(String location) {         Assert.notNull(location, "Location must not be null");         //如果是类路径的方式,那需要使用ClassPathResource 来得到bean 文件的资源对象         if (location.startsWith(CLASSPATH_URL_PREFIX)) {             return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());         }          try {               // 如果是URL 方式,使用UrlResource 作为bean 文件的资源对象              URL url = new URL(location);              return new UrlResource(url);             }             catch (MalformedURLException ex) {            }            //如果既不是classpath标识,又不是URL标识的Resource定位,则调用             //容器本身的getResourceByPath方法获取Resource             return getResourceByPath(location);     }

    程序运行到这,就开始往回返回了,BeanDefinition的Resource已经定位好了,给新创建的BeanFactory加了一个synchronized关键字,保证当前只有一个线程访问。下一篇文章会具体的介绍BeanDefinition的载入和解析。
    
    
    

    
    参考资料:

spring技术内幕–深入解析Spring架构与设计原理
深入分析Java Web技术内幕
Spring:源码解读Spring IOC原理

1 5
原创粉丝点击