当前位置:   article > 正文

SpringBoot IOC容器的初始化流程_springboot初始化核心流程

springboot初始化核心流程

一、Spring 核心容器类

1.1 BeanFactory

  Spring Bean的创建过程是典型的工厂模式,这一系列的Bean工厂,也即IOC容器为开发者管理对象间的依赖关系提供了很多便利和基础服务,在Spring中有许多的IOC容器的实现供用户选择和使用,其相互关系:

  BeanFactory 作为最顶层的一个接口类,它定义了IOC容器的基本功能规范。

  BeanFactory有3个重要的子类:ListableBeanFactory、HierarchicalBeanFactory 和 AutowireCapableBeanFactory。这三个类最终的默认实现类是 DefaultListableBeanFactory,它实现了所有的接口。

  为何要定义这么多层次的接口呢?因为每个接口都有它使用的场合,它主要是为了区分在Spring内部在操作过程中对象的传递和转化过程时,对对象的数据访问所做的限制。

ListableBeanFactory:表示这些Bean是可列表化的;
HierarchicalBeanFactory:表示的是这些Bean是有继承关系的,也就是每个Bean有可能有父Bean;
AutowireCapableBeanFactory:定义Bean的自动装配规则。

  BeanFactory的源码:

publicinterfaceBeanFactory{//对FactoryBean的转义定义,因为如果使用bean的名字检索FactoryBean,得到的对象是工厂生成的对象, //如果需要得到工厂本身,需要转义 String FACTORY_BEAN_PREFIX ="&";//根据bean的名字,获取在IOC容器中得到bean实例 ObjectgetBean(String name)throwsBeansException;//根据bean的名字和Class类型来得到bean实例,增加了类型安全验证机制。 <T>TgetBean(String name,@NullableClass<T> requiredType)throwsBeansException;ObjectgetBean(String name,Object... args)throwsBeansException;<T>TgetBean(Class<T> requiredType)throwsBeansException;<T>TgetBean(Class<T> requiredType,Object... args)throwsBeansException;//提供对 bean 的检索,看看是否在 IOC 容器有这个名字的 bean booleancontainsBean(String name);//根据bean名字得到bean实例,并同时判断这个bean是不是单例 booleanisSingleton(String name)throwsNoSuchBeanDefinitionException;booleanisPrototype(String name)throwsNoSuchBeanDefinitionException;booleanisTypeMatch(String name,ResolvableType typeToMatch)throwsNoSuchBeanDefinitionException;booleanisTypeMatch(String name,@NullableClass<?> typeToMatch)throwsNoSuchBeanDefinitionException;//得到bean实例的Class类型 @NullableClass<?>getType(String name)throwsNoSuchBeanDefinitionException;//得到bean的别名,如果根据别名检索,那么其原名也会被检索出来 String[]getAliases(String name);}

  在BeanFactory里只对IOC容器的基本行为作了定义,根本不关心你的Bean是如何定义怎样加载的。正如我们只关心工厂里得到什么的产品对象,至于工厂是怎么生产这些对象的,这个基本的接口不关心。而要知道工厂是如何产生对象的,我们需要看具体的IOC容器实现。Spring提供了许多IOC容器的实现 ,比如GenericApplicationContext、ClasspathXmlApplicationContext等 。

1.2 ApplicationContext

  ApplicationContext是Spring提供的一个高级的IOC容器,它除了能够提供IOC容器的基本功能外,还为用户提供了以下的附加服务:

1、支持信息源,可以实现国际化。(实现 MessageSource 接口)
2、访问资源。(实现 ResourcePatternResolver 接口)
3、支持应用事件。(实现 ApplicationEventPublisher 接口)

  一般称BeanFactory为IOC容器,而称ApplicationContext为应用上下文,有时候也将ApplicationContext称为Spring容器。

  对于BeanFactory和ApplicationContext的用途:

  BeanFactory是Spring框架的基础设施,面向Spring本身;
  ApplicationContext面向使用Spring框架的开发者,几乎所有的应用场合都可以直接使用Application而非底层的BeanFactory。

  ApplicationContext的接口为:

  1. publicinterfaceApplicationContextextendsEnvironmentCapable,ListableBeanFactory,HierarchicalBeanFactory,
  2. MessageSource,ApplicationEventPublisher,ResourcePatternResolver{
  3. /*返回这个context的唯一id*/
  4. @Nullable
  5. StringgetId();
  6. /*返回这个context所属的应用名称*/
  7. StringgetApplicationName();
  8. /*返回一个context名称*/
  9. StringgetDisplayName();
  10. /*返回context加载的时间*/
  11. longgetStartupDate();
  12. /*返回父类context的上下文*/
  13. @Nullable
  14. ApplicationContextgetParent();
  15. /*公开AutowireCapableBeanFactory接口的能力给到context*/
  16. AutowireCapableBeanFactorygetAutowireCapableBeanFactory()throwsIllegalStateException;

  ApplicationContext继承了HierachicalBeanFactory和ListableBeanFactory接口,在此基础上,还通过其他接口扩展了BeanFactory的功能。ApplicationContext初始化过程:

  在获取ApplicationContext实例后,我们就可以像BeanFactory那样调用getBean(beanName)返回Bean了。ApplicationContext的初始化和BeanFactory初始化有一个重大区别:

BeanFactory在初始化容器时,并没有实例化Bean,直到第一次访问某个Bean时才实例化目标Bean。
ApplicationContext会在初始化应用上下文时就实例化所有单实例的Bean。

  因此,ApplicationContext的初始化时间会比BeanFactory的时间稍微长一些。

1.3 BeanDefinition

  Bean对象在Spring实现中是以BeanDefinition来描述的,其继承体系:

  BeanDefinition,是Spring Bean的建模对象。

  什么是Spring bean的建模对象呢?Class也就是常说的类对象,就是一个普通对象的建模对象,那么为什么Spring不能用Class来建立Bean呢?很简单,因为Class无法完成Bean的抽象,比如Bean的作用域,Bean的注入模型,Bean是否是懒加载等等信息,Class是无法抽象出来的,故而需要一个BeanDefinition类来抽象这些信息,以便于Spring能够完美的实例化一个Bean。

  Bean的解析主要就是对Spring配置文件的解析,这个解析过程主要通过BeanDefintionReader来完成:

二、IOC容器的初始化

  IOC容器的初始化包括BeanDefinition的Resource定位、载入和注册这三个基本的过程。

  ApplicationContext的继承体系:

  ApplicationContext允许上下文嵌套,通过保持父上下文可以维持一个上下文体系。对于Bean的查找可以在这个上下文体系中发生,首先检查当前上下文,其次是父上下文,逐级向上,这样为不同的Spring应用提供了一个共享的Bean定义环境。

2.1 基于Xml的IOC容器的初始化

2.1.1 寻找入口

  以常用的ClassPathXmlApplicationContext为例:

  1. ApplicationContext applicationContext =
  2. newClassPathXmlApplicationContext("application.xml");

  ClassPathXmlApplicationContext继承了AbstractXmlApplicationContext。

  上面的例子中调用的构造函数:

publicClassPathXmlApplicationContext(String configLocation)throwsBeansException{this(newString[]{configLocation},true,(ApplicationContext)null);}

  因此实际调用的构造函数:

publicClassPathXmlApplicationContext(String[] configLocations,boolean refresh,@NullableApplicationContext parent)throwsBeansException{super(parent);this.setConfigLocations(configLocations);if(refresh){this.refresh();}}

  像AnnotationConfigApplicationContext、FileSystemXmlApplicationContext 、XmlWebApplicationContext等,都继承自父容器AbstractApplicationContext,在调用其构造方法时,最终都是调用了refresh()方法。

2.1.2 获得配置路径

  通过分析ClassPathXmlApplicationContext的源代码得知,在创建ClassPathXmlApplicationContext容器时,构造方法做以下两项重要工作:

调用父类容器的构造方法(super(parent)方法),为容器设置好Bean资源加载器。
再调用父类AbstractRefreshableConfigApplicationContext 的 setConfigLocations(configLocations)方法设置Bean配置信息的定位路径。

  追踪ClassPathXmlApplicationContext的继承体系,发现其父类的父类 AbstractApplicationContext 中初始化IOC容器所做的主要源码:

publicabstractclassAbstractApplicationContextextendsDefaultResourceLoaderimplementsConfigurableApplicationContext{//静态初始化块,在整个容器创建过程中只执行一次 static{//为了避免应用程序在Weblogic8.1关闭时出现类加载异常加载问题,加载IOC容 //器关闭事件(ContextClosedEvent)类 ContextClosedEvent.class.getName();}publicAbstractApplicationContext(){this.resourcePatternResolver =getResourcePatternResolver();}publicAbstractApplicationContext(@NullableApplicationContext parent){this();setParent(parent);}//获取一个 Spring Source 的加载器用于读入 Spring Bean 配置信息 protectedResourcePatternResolvergetResourcePatternResolver(){//AbstractApplicationContext继承DefaultResourceLoader,因此也是一个资源加载器 //Spring 资源加载器,其getResource(String location)方法用于载入资源 returnnewPathMatchingResourcePatternResolver(this);}...}

  AbstractApplicationContext 的默认构造方法中有调用 PathMatchingResourcePatternResolver的构造方法创建Spring资源加载器:

publicPathMatchingResourcePatternResolver(ResourceLoader resourceLoader){Assert.notNull(resourceLoader,"ResourceLoader must not be null");//设置Spring的资源加载器 this.resourceLoader = resourceLoader;}

  在设置容器的资源加载器之后,接下来ClassPathXmlApplicationContext执行setConfigLocations()方法通过调用其父类AbstractRefreshableConfigApplicationContext的方法进行对Bean配置信息的定位:

//处理单个资源文件路径为一个字符串的情况 publicvoidsetConfigLocation(String location){//String CONFIG_LOCATION_DELIMITERS = ",; /t/n"; //即多个资源文件路径之间用” ,; tn”分隔,解析成数组形式 setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS));}//解析Bean定义资源文件的路径,处理多个资源文件字符串数组 publicvoidsetConfigLocations(@NullableString... locations){if(locations !=null){Assert.noNullElements(locations,"Config locations must not be null");this.configLocations =newString[locations.length];for(int i =0; i < locations.length; i++){//resolvePath为同一个类中将字符串解析为路径的方法 this.configLocations[i]=resolvePath(locations[i]).trim();}}else{this.configLocations =null;}}

  通过这两个方法的源码我们可以看出,我们既可以使用一个字符串来配置多个Spring Bean配置信息,也可以使用字符串数组,即下面两种方式都是可以的:

  1. ClassPathResource res =newClassPathResource("a.xml,b.xml");
  2. ClassPathResource res =newClassPathResource(newString[]{"a.xml","b.xml"});

  至此,SpringIOC 容器在初始化时将配置的 Bean 配置信息定位为 Spring 封装的Resource。

2.1.3 开始启动【Spring IOC容器初始化主流程】

  Spring IOC容器对Bean配置资源的载入是从refresh()函数开始的,refresh()是一个模板方法,规定了IOC容器的启动流程,有些逻辑要交给其子类去实现。ClassPathXmlApplicationContext通过调用其父类 AbstractApplicationContext的refresh()函数,启动整个IOC容器对Bean定义的载入过程, AbstractApplicationContext中的refresh()中的逻辑处理:

  1. /**
  2. * refresh方法主要为IOC容器Bean的生命周期管理提供条件,在获取了BeanFactory之后都是
  3. * 在向该容器注册信息源和生命周期事件。
  4. * 在创建IOC容器前,如果已经有容器存在,需要把已有的容器销毁和关闭,
  5. * 以保证在refresh()方法之后使用的是新创建的IOC容器。
  6. */@Overridepublicvoidrefresh()throwsBeansException,IllegalStateException{synchronized(this.startupShutdownMonitor){//1、调用容器准备刷新的方法,获取容器的当时时间,同时给容器设置同步标识 prepareRefresh();//2、告诉子类启动refreshBeanFactory()方法,Bean 定义资源文件的载入从 //子类的refreshBeanFactory()方法启动ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();//3、为 BeanFactory 配置容器特性,例如类加载器、事件处理器等 prepareBeanFactory(beanFactory);try{//4、为容器的某些子类指定特殊的BeanPost事件处理器 postProcessBeanFactory(beanFactory);//5、调用所有注册的BeanFactoryPostProcessor的Bean invokeBeanFactoryPostProcessors(beanFactory);//6、为BeanFactory注册BeanPost事件处理器. //BeanPostProcessor是Bean后置处理器,用于监听容器触发的事件 registerBeanPostProcessors(beanFactory);//7、初始化信息源,和国际化相关. initMessageSource();//8、初始化容器事件传播器. initApplicationEventMulticaster();//9、调用子类的某些特殊Bean初始化方法 onRefresh();//10、为事件传播器注册事件监听器.registerListeners();//11、初始化所有剩余的单例 Bean finishBeanFactoryInitialization(beanFactory);//12、初始化容器的生命周期事件处理器,并发布容器的生命周期事件 finishRefresh();}catch(BeansException ex){if(logger.isWarnEnabled()){
  7. logger.warn("Exception encountered during context initialization - "+"cancelling refresh attempt: "+ ex);}
  8. //13、销毁已创建的 Bean
  9. destroyBeans();
  10. //14、取消refresh操作,重置容器的同步标识.
  11. cancelRefresh(ex);
  12. throw ex;}finally{//15、重设公共缓存 resetCommonCaches();}}}

  refresh()方法主要为IOC容器Bean的生命周期管理提供条件,Spring IOC容器载入Bean配置信息,从其子类容器的refreshBeanFactory()方法启动 。

  所以整个refresh()方法中 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();这句以后代码的都是注册容器的信息源和生命周期事件,我们前面说的载入就是从这句代码开始启动。

  refresh()方法的主要作用是:在创建IOC容器前,如果已经有容器存在,则需要把已有的容器销毁和关闭,以保证在refresh之后使用的是新建立起来的IOC容器。

  它类似于对IOC容器的重启,在新建立好的容器中对容器进行初始化,对Bean配置资源进行载入。

2.1.4 创建容器

  AbstractApplicationContext的obtainFreshBeanFactory()方法调用子类容器的 refreshBeanFactory()方法,启动容器载入Bean配置信息的过程:

  1. protectedConfigurableListableBeanFactoryobtainFreshBeanFactory(){//这里使用了委派设计模式,父类定义了抽象的refreshBeanFactory()方法,具体实现调用子类容器的 refreshBeanFactory()方法 refreshBeanFactory();ConfigurableListableBeanFactory beanFactory =getBeanFactory();if(logger.isDebugEnabled()){
  2. logger.debug("Bean factory for "+getDisplayName()+": "+ beanFactory);}return beanFactory;}

  AbstractApplicationContext 类中只抽象定义了 refreshBeanFactory()方法,容器真正调用的是其子类AbstractRefreshableApplicationContext实现的 refreshBeanFactory()方法:

  1. protectedfinalvoidrefreshBeanFactory()throwsBeansException{//如果已经有容器,销毁容器中的 bean,关闭容器 if(hasBeanFactory()){destroyBeans();closeBeanFactory();}try{//创建 IOC 容器 DefaultListableBeanFactory beanFactory =createBeanFactory();
  2. beanFactory.setSerializationId(getId());//对 IOC 容器进行定制化,如设置启动参数,开启注解的自动装配等 customizeBeanFactory(beanFactory);//调用载入Bean定义的方法,主要这里又使用了一个委派模式,在当前类中只定义了抽象的 loadBeanDefinitions方法,具体的实现调用子类容器 loadBeanDefinitions(beanFactory);synchronized(this.beanFactoryMonitor){this.beanFactory = beanFactory;}}catch(IOException ex){thrownewApplicationContextException("I/O error parsing bean definition source for "+getDisplayName(), ex);}}

  在这个方法(refreshBeanFactory)中,先判断BeanFactory是否存在,如果存在则先销毁beans并关闭beanFactory,接着创建DefaultListableBeanFactory,并调用loadBeanDefinitions(beanFactory)装载bean定义。

2.1.5 载入配置路径

  AbstractRefreshableApplicationContext中只定义了抽象的loadBeanDefinitions方法,容器真正调用的是其子类AbstractXmlApplicationContext对该方法的实现:

  1. publicabstractclassAbstractXmlApplicationContextextendsAbstractRefreshableConfigApplicationContext{...//实现父类抽象的载入 Bean 定义方法 @OverrideprotectedvoidloadBeanDefinitions(DefaultListableBeanFactory beanFactory)throwsBeansException,IOException{//创建 XmlBeanDefinitionReader,即创建Bean读取器,并通过回调设置到容器中去,容器使用该读取器读取Bean配置资源 XmlBeanDefinitionReader beanDefinitionReader =newXmlBeanDefinitionReader(beanFactory);//为Bean读取器设置Spring资源加载器,AbstractXmlApplicationContext的 //祖先父类AbstractApplicationContext继承DefaultResourceLoader,因此,容器本身也是一个资源加载器
  2. beanDefinitionReader.setEnvironment(this.getEnvironment());
  3. beanDefinitionReader.setResourceLoader(this);//为Bean读取器设置SAX xml解析器
  4. beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));//当Bean读取器读取Bean定义的Xml资源文件时,启用Xml的校验机制 initBeanDefinitionReader(beanDefinitionReader);//Bean读取器真正实现加载的方法 loadBeanDefinitions(beanDefinitionReader);}protectedvoidinitBeanDefinitionReader(XmlBeanDefinitionReader reader){
  5. reader.setValidating(this.validating);}//Xml Bean读取器加载Bean配置资源 protectedvoidloadBeanDefinitions(XmlBeanDefinitionReader reader)throwsBeansException,IOException{//获取Bean配置资源的定位 Resource[] configResources =getConfigResources();if(configResources !=null){//Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位的Bean配置资源
  6. reader.loadBeanDefinitions(configResources);}// 如果子类中获取的Bean配置资源定位为空,则获取ClassPathXmlApplicationContext // 构造方法中setConfigLocations方法设置的资源 String[] configLocations =getConfigLocations();if(configLocations !=null){
  7. //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位
  8. //的Bean配置资源
  9. reader.loadBeanDefinitions(configLocations);}}//这里又使用了一个委托模式,调用子类的获取Bean配置资源定位的方法 //该方法在ClassPathXmlApplicationContext中进行实现,对于我们 //举例分析源码的ClassPathXmlApplicationContext没有使用该方法 @NullableprotectedResource[]getConfigResources(){returnnull;}}

  以 XmlBean 读取器的其中一种策略 XmlBeanDefinitionReader为例。XmlBeanDefinitionReader 调用其父类AbstractBeanDefinitionReader的reader.loadBeanDefinitions()方法读取Bean配置资源。

  由于我们使用ClassPathXmlApplicationContext作为例子分析,因此getConfigResources的返回值为null,因此程序执行reader.loadBeanDefinitions(configLocations)分支。

2.1.6 分配路径处理策略

  在XmlBeanDefinitionReader的抽象父类AbstractBeanDefinitionReader中定义了载入过程。AbstractBeanDefinitionReader的loadBeanDefinitions()方法:

  1. //重载方法,调用下面的 loadBeanDefinitions(String, Set<Resource>);方法 @OverridepublicintloadBeanDefinitions(String location)throwsBeanDefinitionStoreException{returnloadBeanDefinitions(location,null);}publicintloadBeanDefinitions(String location,@NullableSet<Resource> actualResources)throwsBeanDefinitionStoreException{//获取在 IOC 容器初始化过程中设置的资源加载器 ResourceLoader resourceLoader =getResourceLoader();if(resourceLoader ==null){thrownewBeanDefinitionStoreException("Cannot import bean definitions from location ["+ location +"]: no ResourceLoader available");}if(resourceLoader instanceofResourcePatternResolver){try{//将指定位置的Bean配置信息解析为Spring IOC容器封装的资源 //加载多个指定位置的Bean配置信息 Resource[] resources =((ResourcePatternResolver) resourceLoader).getResources(location);//委派调用其子类XmlBeanDefinitionReader的方法,实现加载功能 int loadCount =loadBeanDefinitions(resources);if(actualResources !=null){for(Resource resource : resources){
  2. actualResources.add(resource);}}if(logger.isDebugEnabled()){
  3. logger.debug("Loaded "+ loadCount +" bean definitions from location pattern ["+ location +"]");}return loadCount;}catch(IOException ex){thrownewBeanDefinitionStoreException("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){
  4. actualResources.add(resource);}if(logger.isDebugEnabled()){
  5. logger.debug("Loaded "+ loadCount +" bean definitions from location ["+ location +"]");}return loadCount;}}//重载方法,调用 loadBeanDefinitions(String); @OverridepublicintloadBeanDefinitions(String... locations)throwsBeanDefinitionStoreException{Assert.notNull(locations,"Location array must not be null");int counter =0;for(String location : locations){
  6. counter +=loadBeanDefinitions(location);}return counter;}

  AbstractRefreshableConfigApplicationContext的loadBeanDefinitions(Resource…resources) 方法实际上是调用 AbstractBeanDefinitionReader的loadBeanDefinitions()方法。

  从对 AbstractBeanDefinitionReader的loadBeanDefinitions()方法源码分析可以看出该方法就做了两件事:

1、首先,调用资源加载器的获取资源方法 resourceLoader.getResource(location),获取到要加载的资源。
2、其次,真正执行加载功能是其子类 XmlBeanDefinitionReader 的 loadBeanDefinitions()方法。

  在loadBeanDefinitions()方法中调用了AbstractApplicationContext的 getResources()方法,跟进去之后发现getResources()方法其实定义在 ResourcePatternResolver中,此时,我们有必要来看一下ResourcePatternResolver的全类图:

  从上面可以看到ResourceLoader与ApplicationContext的继承关系,可以看出其实际调用的是DefaultResourceLoader中的getSource()方法定位Resource。

  因为ClassPathXmlApplicationContext本身就是DefaultResourceLoader的实现类,所以此时又回到了ClassPathXmlApplicationContext中来。

2.1.7 解析配置文件路径

  XmlBeanDefinitionReader通过调用ClassPathXmlApplicationContext的父类 DefaultResourceLoader的getResource()方法获取要加载的资源:

//获取Resource的具体实现方法 @OverridepublicResourcegetResource(String location){Assert.notNull(location,"Location must not be null");for(ProtocolResolver protocolResolver :this.protocolResolvers){Resource resource = protocolResolver.resolve(location,this);if(resource !=null){return resource;}}//如果是类路径的方式,那需要使用ClassPathResource来得到bean文件的资源对象 if(location.startsWith("/")){returngetResourceByPath(location);}elseif(location.startsWith(CLASSPATH_URL_PREFIX)){returnnewClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()),getClassLoader());}else{try{// 如果是URL方式,使用UrlResource作为bean文件的资源对象 URL url =newURL(location);return(ResourceUtils.isFileURL(url)?newFileUrlResource(url):newUrlResource(url));}catch(MalformedURLException ex){//如果既不是classpath标识,又不是URL标识的Resource定位,则调用 //容器本身的getResourceByPath方法获取Resource returngetResourceByPath(location);}}}

  DefaultResourceLoader 提供了 getResourceByPath()方法的实现,就是为了处理既不是 classpath标识,又不是 URL 标识的 Resource 定位这种情况。

protectedResourcegetResourceByPath(String path){returnnewClassPathContextResource(path,getClassLoader());}

  在ClassPathResource中完成了对整个路径的解析。这样,就可以从类路径上对IOC配置文件进行加载,当然我们可以按照这个逻辑从任何地方加载,在Spring中我们看到它提供的各种资源抽象,比如ClassPathResource、URLResource、FileSystemResource 等来供我们使用。

  上面我们看到的是定位Resource的一个过程,而这只是加载过程的一部分。例如FileSystemXmlApplication容器就重写了getResourceByPath()方法:

  1. @OverrideprotectedResourcegetResourceByPath(String path){if(path.startsWith("/")){
  2. path = path.substring(1);}//这里使用文件系统资源对象来定义bean文件 returnnewFileSystemResource(path);}

  通过子类的覆盖,巧妙地完成了将类路径变为文件路径的转换。

2.1.8 开始读取配置内容

  继续回到XmlBeanDefinitionReader的loadBeanDefinitions(Resource …)方法看到代表bean文件的资源定义以后的载入过程。

  1. //XmlBeanDefinitionReader加载资源的入口方法 @OverridepublicintloadBeanDefinitions(Resource resource)throwsBeanDefinitionStoreException{//将读入的XML资源进行特殊编码处理 returnloadBeanDefinitions(newEncodedResource(resource));}//这里是载入XML形式Bean配置信息方法 publicintloadBeanDefinitions(EncodedResource encodedResource)throwsBeanDefinitionStoreException{...try{//将资源文件转为InputStream的IO流 InputStream inputStream = encodedResource.getResource().getInputStream();try{//从InputStream中得到XML的解析源 InputSource inputSource =newInputSource(inputStream);if(encodedResource.getEncoding()!=null){
  2. inputSource.setEncoding(encodedResource.getEncoding());}//这里是具体的读取过程 returndoLoadBeanDefinitions(inputSource, encodedResource.getResource());}finally{//关闭从Resource中得到的IO流
  3. inputStream.close();}}...}//从特定XML文件中实际载入 Bean 配置资源的方法 protectedintdoLoadBeanDefinitions(InputSource inputSource,Resource resource)throwsBeanDefinitionStoreException{try{//将XML文件转换为DOM对象,解析过程由doLoadDocument实现 Document doc =doLoadDocument(inputSource, resource);//这里是启动对Bean定义解析的详细过程,该解析过程会用到Spring的Bean配置规则 returnregisterBeanDefinitions(doc, resource);}...}
  4. protectedDocumentdoLoadDocument(InputSource inputSource,Resource resource)throwsException{
  5. returnthis.documentLoader.loadDocument(inputSource,getEntityResolver(),this.errorHandler,
  6. getValidationModeForResource(resource),isNamespaceAware());
  7. }

  通过源码分析,载入Bean配置信息的最后一步是将Bean配置信息转换为Document对象,该过程由doLoadDocument()方法实现。

2.1.9 准备文档对象

  将Bean配置资源转换成Document对象的代码,是在DefaultDocumentLoader中:

  1. //使用标准的JAXP将载入的Bean配置资源转换成document对象 @OverridepublicDocumentloadDocument(InputSource inputSource,EntityResolver entityResolver,ErrorHandler errorHandler,int validationMode,boolean namespaceAware)throwsException{//创建文件解析器工厂 DocumentBuilderFactory factory =createDocumentBuilderFactory(validationMode, namespaceAware);if(logger.isDebugEnabled()){
  2. logger.debug("Using JAXP provider ["+ factory.getClass().getName()+"]");}//创建文档解析器 DocumentBuilder builder =createDocumentBuilder(factory, entityResolver, errorHandler);//解析Spring的Bean配置资源 return builder.parse(inputSource);}protectedDocumentBuilderFactorycreateDocumentBuilderFactory(int validationMode,boolean namespaceAware)throwsParserConfigurationException{//创建文档解析工厂 DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
  3. factory.setNamespaceAware(namespaceAware);//设置解析XML的校验 if(validationMode !=XmlValidationModeDetector.VALIDATION_NONE){
  4. factory.setValidating(true);if(validationMode ==XmlValidationModeDetector.VALIDATION_XSD){
  5. factory.setNamespaceAware(true);try{
  6. factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);}catch(IllegalArgumentException ex){ParserConfigurationException pcex =newParserConfigurationException("Unable to validate using XSD: Your JAXP provider ["+ factory +"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? "+"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
  7. pcex.initCause(ex);throw pcex;}}}return factory;}

  至此Spring IOC容器根据定位的Bean配置信息,将其加载读入并转换成为Document对象过程完成。

  接下来我们要继续分析Spring IOC容器将载入的Bean配置信息转换为Document对象之后,是如何将其解析为Spring IOC管理的Bean对象并将其注册到容器中的。

2.1.10 分配解析策略

  XmlBeanDefinitionReader类中的doLoadBeanDefinition()方法,是从特定XML文件中实际载入Bean配置资源的方法,该方法在载入Bean配置资源之后将其转换为Document对象。

  接下来调用registerBeanDefinitions()启动Spring IOC容器对Bean定义的解析过程:

  1. //从特定XML文件中实际载入Bean配置资源的方法
  2. protectedintdoLoadBeanDefinitions(InputSource inputSource,Resource resource)
  3. throwsBeanDefinitionStoreException{
  4. try{
  5. // 将XML文件转换为DOM对象,解析过程由documentLoader方法实现
  6. Document doc =doLoadDocument(inputSource, resource);
  7. // 启动对Bean定义解析的详细过程,该解析过程会用到Spring的Bean配置规则
  8. int count =registerBeanDefinitions(doc, resource);
  9. if(logger.isDebugEnabled()){
  10. logger.debug("Loaded "+ count +" bean definitions from "+ resource);
  11. }
  12. return count;
  13. }
  14. catch(BeanDefinitionStoreException ex){
  15. throw ex;
  16. }
  17. catch(SAXParseException ex){
  18. thrownewXmlBeanDefinitionStoreException(resource.getDescription(),
  19. "Line "+ ex.getLineNumber()+" in XML document from "+ resource +" is invalid", ex);
  20. }
  21. catch(SAXException ex){
  22. thrownewXmlBeanDefinitionStoreException(resource.getDescription(),
  23. "XML document from "+ resource +" is invalid", ex);
  24. }
  25. catch(ParserConfigurationException ex){
  26. thrownewBeanDefinitionStoreException(resource.getDescription(),
  27. "Parser configuration exception parsing XML from "+ resource, ex);
  28. }
  29. catch(IOException ex){
  30. thrownewBeanDefinitionStoreException(resource.getDescription(),
  31. "IOException parsing XML document from "+ resource, ex);
  32. }
  33. catch(Throwable ex){
  34. thrownewBeanDefinitionStoreException(resource.getDescription(),
  35. "Unexpected exception parsing XML document from "+ resource, ex);
  36. }
  37. }//按照Spring的Bean语义要求,将Bean配置资源解析并转换为容器内部数据结构 publicintregisterBeanDefinitions(Document doc,Resource resource)throwsBeanDefinitionStoreException{//得到BeanDefinitionDocumentReader来对xml格式的BeanDefinition解析 BeanDefinitionDocumentReader documentReader =createBeanDefinitionDocumentReader();//获得容器中注册的Bean数量 int countBefore =getRegistry().getBeanDefinitionCount();//解析过程入口,这里使用了委派模式,BeanDefinitionDocumentReader只是个接口, //具体的解析实现过程有实现类DefaultBeanDefinitionDocumentReader完成
  38. documentReader.registerBeanDefinitions(doc,createReaderContext(resource));//统计解析的Bean数量 returngetRegistry().getBeanDefinitionCount()- countBefore;}

  Bean配置资源的载入解析分为以下两个过程:

通过调用XML解析器将Bean配置信息转换得到Document对象,但是这些Document对象并没有按照Spring 的Bean规则进行解析。这一步是载入的过程 。
在完成通用的XML解析之后,按照Spring Bean的定义规则对Document对象进行解析,其解析过程是在接口BeanDefinitionDocumentReader的实现类DefaultBeanDefinitionDocumentReader 中实现。
2.1.11 将配置载入内存

  BeanDefinitionDocumentReader接口通过registerBeanDefinitions()方法,调用其实现类DefaultBeanDefinitionDocumentReader对Document对象进行解析:

  1. //根据Spring DTD对Bean的定义规则解析Bean定义Document对象
  2. @Override
  3. publicvoidregisterBeanDefinitions(Document doc,XmlReaderContext readerContext){
  4. //获得XML描述符
  5. this.readerContext = readerContext;
  6. //获取document的根元素
  7. doRegisterBeanDefinitions(doc.getDocumentElement());
  8. }
  9. @SuppressWarnings("deprecation")
  10. protectedvoiddoRegisterBeanDefinitions(Element root){
  11. // 具体的解析过程由BeanDefinitionParserDelegate实现,其中定义了Spring Bean定义XML文件的各种元素
  12. BeanDefinitionParserDelegate parent =this.delegate;
  13. this.delegate =createDelegate(getReaderContext(), root, parent);
  14. if(this.delegate.isDefaultNamespace(root)){
  15. //处理profile属性
  16. String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
  17. if(StringUtils.hasText(profileSpec)){
  18. String[] specifiedProfiles =StringUtils.tokenizeToStringArray(
  19. profileSpec,BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
  20. if(!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)){
  21. if(logger.isDebugEnabled()){
  22. logger.debug("Skipped XML bean definition file due to specified profiles ["+ profileSpec +
  23. "] not matching: "+getReaderContext().getResource());
  24. }
  25. return;
  26. }
  27. }
  28. }
  29. //在解析Bean定义之前,进行自定义解析,增强解析过程的可扩展性
  30. preProcessXml(root);
  31. //从文档的根元素开始进行Bean定义的文档对象的解析
  32. parseBeanDefinitions(root,this.delegate);
  33. //在解析Bean定义之后,进行自定义解析,增加解析过程的可扩展性
  34. postProcessXml(root);
  35. this.delegate = parent;
  36. }
  37. //创建BeanDefinitionParserDelegate,用于完成真正的解析过程
  38. protectedBeanDefinitionParserDelegatecreateDelegate(
  39. XmlReaderContext readerContext,Element root,@NullableBeanDefinitionParserDelegate parentDelegate){
  40. BeanDefinitionParserDelegate delegate =newBeanDefinitionParserDelegate(readerContext);
  41. //BeanDefinitionParserDelegate初始化document根元素
  42. delegate.initDefaults(root, parentDelegate);
  43. return delegate;
  44. }
  45. //使用Spring的Bean规则从文档的根元素开始Bean定义的文档对象的解析
  46. protectedvoidparseBeanDefinitions(Element root,BeanDefinitionParserDelegate delegate){
  47. //Bean定义的文档对象使用了Spring默认的XML命名空间
  48. if(delegate.isDefaultNamespace(root)){
  49. //获取Bean定义的文档对象根元素的所有子节点
  50. NodeList nl = root.getChildNodes();
  51. for(int i =0; i < nl.getLength(); i++){
  52. Node node = nl.item(i);
  53. //获取的文档节点是XML元素节点
  54. if(node instanceofElement){
  55. Element ele =(Element) node;
  56. //对bean的处理
  57. if(delegate.isDefaultNamespace(ele)){
  58. //使用Spring的Bean规则解析元素节点
  59. parseDefaultElement(ele, delegate);
  60. }else{
  61. //如果没有使用Spring默认的XML命名空间,则使用用户自定义的解析规则解析元素节点
  62. delegate.parseCustomElement(ele);
  63. }
  64. }
  65. }
  66. }else{
  67. //Document的根节点没有使用Spring默认的命名空间,使用自定义的解析规则解析Document的根节点
  68. delegate.parseCustomElement(root);
  69. }
  70. }
  71. //使用Spring的Bean规则解析文档元素节点
  72. privatevoidparseDefaultElement(Element ele,BeanDefinitionParserDelegate delegate){
  73. //如果元素节点是<Import>导入元素,进行导入解析
  74. if(delegate.nodeNameEquals(ele, IMPORT_ELEMENT)){
  75. importBeanDefinitionResource(ele);
  76. }
  77. //如果元素节点是<Alias>导入元素,进行别名解析
  78. elseif(delegate.nodeNameEquals(ele, ALIAS_ELEMENT)){
  79. processAliasRegistration(ele);
  80. }
  81. //如果元素节点是<Bean>导入元素,按照Spring的Bean规则解析元素
  82. elseif(delegate.nodeNameEquals(ele, BEAN_ELEMENT)){
  83. processBeanDefinition(ele, delegate);
  84. }
  85. elseif(delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)){
  86. doRegisterBeanDefinitions(ele);
  87. }
  88. }
  89. //解析<import>导入元素,从给定的导入路径加载Bean资源到Spring IOC容器中
  90. protectedvoidimportBeanDefinitionResource(Element ele){
  91. //获取给定的导入元素的location属性
  92. String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
  93. //如果导入元素的location属性为空,则没有导入任何资源,直接返回
  94. if(!StringUtils.hasText(location)){
  95. getReaderContext().error("Resource location must not be empty", ele);
  96. return;
  97. }
  98. //使用系统变量值解析location属性值
  99. location =getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
  100. Set<Resource> actualResources =newLinkedHashSet<>(4);
  101. //标识给定的导入元素的location属性值是否是绝对路径
  102. boolean absoluteLocation =false;
  103. try{
  104. absoluteLocation =ResourcePatternUtils.isUrl(location)||ResourceUtils.toURI(location).isAbsolute();
  105. }catch(URISyntaxException ex){
  106. }
  107. // 给定的导入元素的location属性值是绝对路径
  108. if(absoluteLocation){
  109. try{
  110. //使用资源读入器加载给定路径的Bean资源
  111. int importCount =getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
  112. if(logger.isTraceEnabled()){
  113. logger.trace("Imported "+ importCount +" bean definitions from URL location ["+ location +"]");
  114. }
  115. }catch(BeanDefinitionStoreException ex){
  116. getReaderContext().error(
  117. "Failed to import bean definitions from URL location ["+ location +"]", ele, ex);
  118. }
  119. }else{
  120. // 给定的导入元素的location属性值是相对路径
  121. try{
  122. int importCount;
  123. //将给定导入元素的location封装为相对路径
  124. Resource relativeResource =getReaderContext().getResource().createRelative(location);
  125. if(relativeResource.exists()){
  126. //使用资源读入器加载Bean资源
  127. importCount =getReaderContext().getReader().loadBeanDefinitions(relativeResource);
  128. actualResources.add(relativeResource);
  129. }
  130. //封装的相对路径资源不存在
  131. else{
  132. //获取Spring IOC容器资源读入器的基本路径
  133. String baseLocation =getReaderContext().getResource().getURL().toString();
  134. //根据Spring IOC容器资源读入器的基本路径加载给定导入路径的资源
  135. importCount =getReaderContext().getReader().loadBeanDefinitions(
  136. StringUtils.applyRelativePath(baseLocation, location), actualResources);
  137. }
  138. if(logger.isTraceEnabled()){
  139. logger.trace("Imported "+ importCount +" bean definitions from relative location ["+ location +"]");
  140. }
  141. }catch(IOException ex){
  142. getReaderContext().error("Failed to resolve current resource location", ele, ex);
  143. }catch(BeanDefinitionStoreException ex){
  144. getReaderContext().error(
  145. "Failed to import bean definitions from relative location ["+ location +"]", ele, ex);
  146. }
  147. }
  148. Resource[] actResArray = actualResources.toArray(newResource[0]);
  149. //在解析完import元素之后,发送容器导入其他资源处理完成事件
  150. getReaderContext().fireImportProcessed(location, actResArray,extractSource(ele));
  151. }
  152. //解析alias别名元素,为Bean向IOC容器注册别名
  153. protectedvoidprocessAliasRegistration(Element ele){
  154. //获取<alias>别名元素中name的属性值
  155. String name = ele.getAttribute(NAME_ATTRIBUTE);
  156. //获取<alias>别名元素中alias的属性值
  157. String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
  158. boolean valid =true;
  159. //别名元素的name属性值为空
  160. if(!StringUtils.hasText(name)){
  161. getReaderContext().error("Name must not be empty", ele);
  162. valid =false;
  163. }
  164. //alias别名元素的alias属性值为空
  165. if(!StringUtils.hasText(alias)){
  166. getReaderContext().error("Alias must not be empty", ele);
  167. valid =false;
  168. }
  169. if(valid){
  170. try{
  171. //向容器的资源读入器注册别名
  172. getReaderContext().getRegistry().registerAlias(name, alias);
  173. }catch(Exception ex){
  174. getReaderContext().error("Failed to register alias '"+ alias +
  175. "' for bean with name '"+ name +"'", ele, ex);
  176. }
  177. //在解析完成<alias>元素之后,发送容器别名处理完成事件
  178. getReaderContext().fireAliasRegistered(name, alias,extractSource(ele));
  179. }
  180. }
  181. //解析Bean资源文档对象的普通元素
  182. protectedvoidprocessBeanDefinition(Element ele,BeanDefinitionParserDelegate delegate){
  183. BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
  184. //BeanDefinitionHolder是对BeanDefinition的封装,即Bean定义的封装类
  185. //对文档对象中bean元素的解析由BeanDefinitionParserDelegate实现
  186. if(bdHolder !=null){
  187. bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
  188. try{
  189. //向Spring IOC容器注册解析得到的Bean定义,这是Bean定义向IOC容器注册的入口
  190. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder,getReaderContext().getRegistry());
  191. }catch(BeanDefinitionStoreException ex){
  192. getReaderContext().error("Failed to register bean definition with name '"+
  193. bdHolder.getBeanName()+"'", ele, ex);
  194. }
  195. //在完成向Spring IOC容器注册解析得到的Bean定义之后,发送注册事件
  196. getReaderContext().fireComponentRegistered(newBeanComponentDefinition(bdHolder));
  197. }
  198. }

  我们使用Spring时,在Spring配置文件中可以使用<import>元素来导入IOC容器所需要的其他资源,Spring IOC容器在解析时会首先将指定导入的资源加载进容器中。

  使用<ailas>别名时,Spring IOC容器首先将别名元素所定义的别名注册到容器中。

  对于既不是<import>元素,又不是<alias>元素的元素,即Spring配置文件中普通的<bean>元素的解析由BeanDefinitionParserDelegate类的parseBeanDefinitionElement()方法来实现。

2.1.12 载入< bean >元素

  Bean 配置信息中的<import>和<alias>元素解析在DefaultBeanDefinitionDocumentReader 中已经完成,对Bean配置信息中使用最多的<bean>元素交由BeanDefinitionParserDelegate来解析:

  1. //解析<bean>元素的入口
  2. @Nullable
  3. publicBeanDefinitionHolderparseBeanDefinitionElement(Element ele){
  4. returnparseBeanDefinitionElement(ele,null);
  5. }
  6. //解析Bean配置信息中的<bean>元素,这个方法中主要处理bean中的id,name和别名属性
  7. @Nullable
  8. publicBeanDefinitionHolderparseBeanDefinitionElement(Element ele,@NullableBeanDefinition containingBean){
  9. //获取<Bean>元素中的id属性值
  10. String id = ele.getAttribute(ID_ATTRIBUTE);
  11. //获取<Bean>元素中的name属性值
  12. String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
  13. //获取<Bean>元素中的alias属性值
  14. List<String> aliases =newArrayList<>();
  15. if(StringUtils.hasLength(nameAttr)){
  16. String[] nameArr =StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
  17. aliases.addAll(Arrays.asList(nameArr));
  18. }
  19. String beanName = id;
  20. //如果<bean>元素中没有配置id属性,将别名中的第一个值赋值给beanName
  21. if(!StringUtils.hasText(beanName)&&!aliases.isEmpty()){
  22. beanName = aliases.remove(0);
  23. if(logger.isTraceEnabled()){
  24. logger.trace("No XML 'id' specified - using '"+ beanName +
  25. "' as bean name and "+ aliases +" as aliases");
  26. }
  27. }
  28. //检查<bean>元素所配置的id和name的唯一性,containingBean标识<bean>元素中是否包含子<bean>元素
  29. if(containingBean ==null){
  30. //检查<bean>元素所排位置的id,name,或者别名是否重复
  31. checkNameUniqueness(beanName, aliases, ele);
  32. }
  33. //详细对<bean>元素中配置的Bean定义进行解析
  34. AbstractBeanDefinition beanDefinition =parseBeanDefinitionElement(ele, beanName, containingBean);
  35. if(beanDefinition !=null){
  36. if(!StringUtils.hasText(beanName)){
  37. try{
  38. //如果不存在id,name,alias属性,且没有包含子元素,那么
  39. //根据spring中提供的命名规则为当前bean生成对应的beanName
  40. if(containingBean !=null){
  41. beanName =BeanDefinitionReaderUtils.generateBeanName(
  42. beanDefinition,this.readerContext.getRegistry(),true);
  43. }
  44. else{
  45. //如果bean元素中没有配置id,name,alias,且包含了子元素,则
  46. //将解析的Bean使用别名向IOC容器注册
  47. beanName =this.readerContext.generateBeanName(beanDefinition);
  48. //为解析的Bean使用别名注册时,为了向后兼容Spring1.2/2.0,给别名添加类名后缀
  49. String beanClassName = beanDefinition.getBeanClassName();
  50. if(beanClassName !=null&&
  51. beanName.startsWith(beanClassName)&& beanName.length()> beanClassName.length()&&
  52. !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)){
  53. aliases.add(beanClassName);
  54. }
  55. }
  56. if(logger.isTraceEnabled()){
  57. logger.trace("Neither XML 'id' nor 'name' specified - "+
  58. "using generated bean name ["+ beanName +"]");
  59. }
  60. }
  61. catch(Exception ex){
  62. error(ex.getMessage(), ele);
  63. returnnull;
  64. }
  65. }
  66. String[] aliasesArray =StringUtils.toStringArray(aliases);
  67. returnnewBeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
  68. }
  69. //当解析出错的时候,返回null
  70. returnnull;
  71. }
  72. protectedvoidcheckNameUniqueness(String beanName,List<String> aliases,Element beanElement){
  73. String foundName =null;
  74. if(StringUtils.hasText(beanName)&&this.usedNames.contains(beanName)){
  75. foundName = beanName;
  76. }
  77. if(foundName ==null){
  78. foundName =CollectionUtils.findFirstMatch(this.usedNames, aliases);
  79. }
  80. if(foundName !=null){
  81. error("Bean name '"+ foundName +"' is already used in this <beans> element", beanElement);
  82. }
  83. this.usedNames.add(beanName);
  84. this.usedNames.addAll(aliases);
  85. }
  86. //详细对bean元素中配置的bean定义的其他属性进行解析,主要处理id,name,alias的其他属性
  87. @Nullable
  88. publicAbstractBeanDefinitionparseBeanDefinitionElement(
  89. Element ele,String beanName,@NullableBeanDefinition containingBean){
  90. //记录解析的bean元素
  91. this.parseState.push(newBeanEntry(beanName));
  92. //只读取bean元素中配置的class名字,然后载入BeanDefinition中,只是记录配置
  93. //的class名字,不做实例化,对象的实例化在依赖注入时完成
  94. String className =null;
  95. //解析class属性
  96. if(ele.hasAttribute(CLASS_ATTRIBUTE)){
  97. className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
  98. }
  99. String parent =null;
  100. //解析parent属性
  101. if(ele.hasAttribute(PARENT_ATTRIBUTE)){
  102. parent = ele.getAttribute(PARENT_ATTRIBUTE);
  103. }
  104. try{
  105. //创建用于承载属性的AbstractBeanDefinition类型的GenericBeanDefinition,为载入Bean定义信息做准备
  106. AbstractBeanDefinition bd =createBeanDefinition(className, parent);
  107. //对bean元素中配置的一些属性进行解析和设置,如是否单例
  108. parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
  109. //为bean元素解析的bean设置描述信息
  110. bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
  111. //对<Bean>元素的meta(元信息)属性解析
  112. parseMetaElements(ele, bd);
  113. //对<Bean>元素的lookup-method属性解析
  114. parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
  115. //对<Bean>元素的replaced-method属性解析
  116. parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
  117. //解析构造函数参数
  118. parseConstructorArgElements(ele, bd);
  119. //解析<property>元素
  120. parsePropertyElements(ele, bd);
  121. //解析<qualifier>元素
  122. parseQualifierElements(ele, bd);
  123. //为当前解析的bean设置所需的资源和依赖对象
  124. bd.setResource(this.readerContext.getResource());
  125. bd.setSource(extractSource(ele));
  126. return bd;
  127. }
  128. catch(ClassNotFoundException ex){
  129. error("Bean class ["+ className +"] not found", ele, ex);
  130. }
  131. catch(NoClassDefFoundError err){
  132. error("Class that bean class ["+ className +"] depends on not found", ele, err);
  133. }
  134. catch(Throwable ex){
  135. error("Unexpected failure during bean definition parsing", ele, ex);
  136. }
  137. finally{
  138. this.parseState.pop();
  139. }
  140. //当解析bean元素出错时,返回null
  141. returnnull;
  142. }

  通过对上述源码的分析,就会明白我们在Spring配置文件中<Bean>元素的中配置的属性就是通过该方法解析和设置到Bean中去的。

  在解析<Bean>元素过程中没有创建和实例化Bean对象,只是创建了Bean对象的定义类BeanDefinition,将<Bean>元素中的配置信息设置到BeanDefinition中作为记录,当依赖注入时才使用这些记录信息创建和实例化具体的Bean对象。

2.1.13 载入< property >元素

  BeanDefinitionParserDelegate在解析<Bean>调用parsePropertyElements()方法解析<Bean>元素中的<property>属性子元素:

  1. /**
  2. * 解析<bean>元素中所有的<property>子元素
  3. */
  4. publicvoidparsePropertyElements(Element beanEle,BeanDefinition bd){
  5. //获取<bean>元素的所有子元素
  6. NodeList nl = beanEle.getChildNodes();
  7. for(int i =0; i < nl.getLength(); i++){
  8. Node node = nl.item(i);
  9. //如果子元素是<property>子元素,则调用下面方法进行<property>子元素解析
  10. if(isCandidateElement(node)&&nodeNameEquals(node, PROPERTY_ELEMENT)){
  11. parsePropertyElement((Element) node, bd);
  12. }
  13. }
  14. }
  15. //解析<property>元素
  16. publicvoidparsePropertyElement(Element ele,BeanDefinition bd){
  17. //获取<property>元素的名字
  18. String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
  19. if(!StringUtils.hasLength(propertyName)){
  20. error("Tag 'property' must have a 'name' attribute", ele);
  21. return;
  22. }
  23. this.parseState.push(newPropertyEntry(propertyName));
  24. try{
  25. //如果一个bean中已经有同名的property属性存在则不进行解析,直接返回,
  26. //即如果配置了多个同名的属性则第一个起作用
  27. if(bd.getPropertyValues().contains(propertyName)){
  28. error("Multiple 'property' definitions for property '"+ propertyName +"'", ele);
  29. return;
  30. }
  31. //解析获取property元素的值
  32. Object val =parsePropertyValue(ele, bd, propertyName);
  33. //根据property元素的名字和值创建实例
  34. PropertyValue pv =newPropertyValue(propertyName, val);
  35. //解析<property>元素的属性
  36. parseMetaElements(ele, pv);
  37. pv.setSource(extractSource(ele));
  38. bd.getPropertyValues().addPropertyValue(pv);
  39. }
  40. finally{
  41. this.parseState.pop();
  42. }
  43. }
  44. //解析获取property元素的值
  45. @Nullable
  46. publicObjectparsePropertyValue(Element ele,BeanDefinition bd,@NullableString propertyName){
  47. String elementName =(propertyName !=null?
  48. "<property> element for property '"+ propertyName +"'":
  49. "<constructor-arg> element");
  50. // Should only have one child element: , etc.
  51. //获取<property>的所有子元素,只能是其中一种类型:ref, value, list等
  52. NodeList nl = ele.getChildNodes();
  53. Element subElement =null;
  54. for(int i =0; i < nl.getLength(); i++){
  55. Node node = nl.item(i);
  56. //子元素不是description和meta属性
  57. if(node instanceofElement&&!nodeNameEquals(node, DESCRIPTION_ELEMENT)&&
  58. !nodeNameEquals(node, META_ELEMENT)){
  59. if(subElement !=null){
  60. error(elementName +" must not contain more than one sub-element", ele);
  61. }
  62. else{
  63. //当前property元素包含子元素
  64. subElement =(Element) node;
  65. }
  66. }
  67. }
  68. //判断属性值是ref还是value,不允许既是ref又是value
  69. boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
  70. boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
  71. if((hasRefAttribute && hasValueAttribute)||
  72. ((hasRefAttribute || hasValueAttribute)&& subElement !=null)){
  73. error(elementName +
  74. " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
  75. }
  76. //如果属性值是ref,创建一个ref的数据对象RuntimeBeanReference
  77. //这个对象封装了ref信息
  78. if(hasRefAttribute){
  79. String refName = ele.getAttribute(REF_ATTRIBUTE);
  80. if(!StringUtils.hasText(refName)){
  81. error(elementName +" contains empty 'ref' attribute", ele);
  82. }
  83. //一个指向运行时所依赖对象的引用
  84. RuntimeBeanReference ref =newRuntimeBeanReference(refName);
  85. //设置这个ref的数据对象被当前对象所引用
  86. ref.setSource(extractSource(ele));
  87. return ref;
  88. }
  89. //如果属性值是value,创建一个value的数据对象TypedStringValue
  90. //这个对象封装了value信息
  91. elseif(hasValueAttribute){
  92. //一个持有Strig类型值的对象
  93. TypedStringValue valueHolder =newTypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
  94. //设置这个value的数据对象被当前对象所引用
  95. valueHolder.setSource(extractSource(ele));
  96. return valueHolder;
  97. }
  98. //如果当前property元素还有子元素
  99. elseif(subElement !=null){
  100. //解析<property>的子元素
  101. returnparsePropertySubElement(subElement, bd);
  102. }
  103. else{
  104. //属性值既不是ref也不是value,解析出错,返回null
  105. error(elementName +" must specify a ref or value", ele);
  106. returnnull;
  107. }
  108. }

  在Spring配置文件中,<Bean>元素中<property>元素的相关配置是如何处理的:

ref被封装为指向依赖对象一个引用。
value配置都会封装成一个字符串类型的对象。
ref和value都通过“解析的数据类型属性值.setSource(extractSource(ele));”方法将属性值/引用与所引用的属性关联起来。

  在方法的最后对于<property>元素的子元素通过parsePropertySubElement ()方法解析,我们继续分析该方法的源码,了解其解析过程。

2.1.14 载入< property >的子元素

  在BeanDefinitionParserDelegate类中的parsePropertySubElement()方法对<property>中的子元素解析:

  1. //解析property元素中的ref、value或者集合等子元素
  2. @Nullable
  3. publicObjectparsePropertySubElement(Element ele,@NullableBeanDefinition bd,@NullableString defaultValueType){
  4. //如果<property>元素没有使用Spring默认的命名空间,则使用用户自定义的规则解析内嵌元素
  5. if(!isDefaultNamespace(ele)){
  6. returnparseNestedCustomElement(ele, bd);
  7. }
  8. //如果子元素是bean,则使用解析bean元素的方法解析
  9. elseif(nodeNameEquals(ele, BEAN_ELEMENT)){
  10. BeanDefinitionHolder nestedBd =parseBeanDefinitionElement(ele, bd);
  11. if(nestedBd !=null){
  12. nestedBd =decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
  13. }
  14. return nestedBd;
  15. }
  16. //如果子元素的ref,ref只能有三个属性,bean,local,parent
  17. elseif(nodeNameEquals(ele, REF_ELEMENT)){
  18. // A generic reference to any name of any bean.
  19. String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);
  20. boolean toParent =false;
  21. if(!StringUtils.hasLength(refName)){
  22. //获取property元素的parent属性值,引用父容器中的Bean
  23. refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);
  24. toParent =true;
  25. if(!StringUtils.hasLength(refName)){
  26. error("'bean' or 'parent' is required for <ref> element", ele);
  27. returnnull;
  28. }
  29. }
  30. if(!StringUtils.hasText(refName)){
  31. error("<ref> element contains empty target attribute", ele);
  32. returnnull;
  33. }
  34. //创建ref类型数据,指向被引用的对象
  35. RuntimeBeanReference ref =newRuntimeBeanReference(refName, toParent);
  36. //设置引用类型值被当前子元素所引用
  37. ref.setSource(extractSource(ele));
  38. return ref;
  39. }
  40. //如果子元素是<idref>,使用解析ref元素的方法解析
  41. elseif(nodeNameEquals(ele, IDREF_ELEMENT)){
  42. returnparseIdRefElement(ele);
  43. }
  44. //如果子元素是<value>,则使用解析value元素的方法解析
  45. elseif(nodeNameEquals(ele, VALUE_ELEMENT)){
  46. returnparseValueElement(ele, defaultValueType);
  47. }
  48. //如果子元素是null,为property元素设置一个封装null值的字符串数据
  49. elseif(nodeNameEquals(ele, NULL_ELEMENT)){
  50. TypedStringValue nullHolder =newTypedStringValue(null);
  51. nullHolder.setSource(extractSource(ele));
  52. return nullHolder;
  53. }
  54. //如果子元素是<array>,使用解析array集合子元素的方法解析
  55. elseif(nodeNameEquals(ele, ARRAY_ELEMENT)){
  56. returnparseArrayElement(ele, bd);
  57. }
  58. //如果子元素是<list>,使用解析list集合子元素的方法解析
  59. elseif(nodeNameEquals(ele, LIST_ELEMENT)){
  60. returnparseListElement(ele, bd);
  61. }
  62. //如果子元素是<set>,使用解析set集合子元素的方法解析
  63. elseif(nodeNameEquals(ele, SET_ELEMENT)){
  64. returnparseSetElement(ele, bd);
  65. }
  66. //如果子元素是<map>,使用解析map集合子元素的方法解析
  67. elseif(nodeNameEquals(ele, MAP_ELEMENT)){
  68. returnparseMapElement(ele, bd);
  69. }
  70. //如果子元素是<props>,使用解析props集合子元素的方法解析
  71. elseif(nodeNameEquals(ele, PROPS_ELEMENT)){
  72. returnparsePropsElement(ele);
  73. }
  74. //既不是ref,又不是value,也不是集合,则子元素配置错误,返回null
  75. else{
  76. error("Unknown property sub-element: ["+ ele.getNodeName()+"]", ele);
  77. returnnull;
  78. }
  79. }

  在Spring配置文件中,对<property>元素中配置的array、list、set、map、prop等各种集合子元素的都通过上述方法解析,生成对应的数据对象,比如ManagedList、 ManagedArray、ManagedSet 等,这些Managed类是Spring对象BeanDefiniton的数据封装,对集合数据类型的具体解析有各自的解析方法实现,解析方法的命名非常规范,一目了然,我们对<list>集合元素的解析方法进行源码分析,了解其实现过程。

2.1.15 载入< list >子元素

  在BeanDefinitionParserDelegate类中的parseListElement()方法就是具体实现解析<property>元素中的<list>集合子元素:

  1. //解析<list>集合子元素
  2. publicList<Object>parseListElement(Element collectionEle,@NullableBeanDefinition bd){
  3. //获取<list>元素的value-type属性,即获取集合元素的数据类型
  4. String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
  5. //获取<list>集合子元素中的所有子节点
  6. NodeList nl = collectionEle.getChildNodes();
  7. //Spring将list封装成ManagedList对象
  8. ManagedList<Object> target =newManagedList<>(nl.getLength());
  9. target.setSource(extractSource(collectionEle));
  10. //设置集合目标数据类型
  11. target.setElementTypeName(defaultElementType);
  12. target.setMergeEnabled(parseMergeAttribute(collectionEle));
  13. //具体的<list>元素解析
  14. parseCollectionElements(nl, target, bd, defaultElementType);
  15. return target;
  16. }
  17. //具体解析list集合子元素,<array>,<list>,<set>都用该方法解析
  18. protectedvoidparseCollectionElements(
  19. NodeList elementNodes,Collection<Object> target,@NullableBeanDefinition bd,String defaultElementType){
  20. //遍历集合的所有节点
  21. for(int i =0; i < elementNodes.getLength(); i++){
  22. Node node = elementNodes.item(i);
  23. //节点不是description节点
  24. if(node instanceofElement&&!nodeNameEquals(node, DESCRIPTION_ELEMENT)){
  25. //将解析的元素加入集合,递归调用下一个子元素
  26. target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
  27. }
  28. }
  29. }

  经过对Spring Bean配置信息转换的Document对象中的元素层层解析,Spring IOC现在已经将 XML形式定义的Bean配置信息转换为Spring IOC所识别的数据结构——BeanDefinition,它是 Bean 配置信息中配置的 POJO 对象在Spring IOC容器中的映射,我们可以通过AbstractBeanDefinition为入口,看到了IOC容器进行索引、查询和操作。

  通过Spring IOC容器对Bean配置资源的解析后,IOC容器大致完成了管理Bean对象的准备工作,即初始化过程,但是最为重要的依赖注入还没有发生,现在在IOC容器中BeanDefinition存储的只是一些静态信息,接下来需要向容器注册Bean定义信息才能全部完成IOC容器的初始化过程。

2.1.16 分配注册策略

  接下来我们来分析DefaultBeanDefinitionDocumentReader对Bean定义转换的Document对象解析的流程中, 在其parseDefaultElement() 方法中完成对Document对象的解析后得到封装BeanDefinition的BeanDefinitionHold对象 , 然后调用BeanDefinitionReaderUtils的registerBeanDefinition()方向IOC容器注册解析的Bean:

  1. //将解析的BeanDefinitionHold 注册到容器中
  2. publicstaticvoidregisterBeanDefinition(
  3. BeanDefinitionHolder definitionHolder,BeanDefinitionRegistry registry)
  4. throwsBeanDefinitionStoreException{
  5. //获取解析的BeanDefinition的名称
  6. String beanName = definitionHolder.getBeanName();
  7. //向Spring IOC容器注册BeanDefinition
  8. registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
  9. // Register aliases for bean name, if any.
  10. // 如果解析的BeanDefinition有别名,向Spring IOC容器注册别名
  11. String[] aliases = definitionHolder.getAliases();
  12. if(aliases !=null){
  13. for(String alias : aliases){
  14. registry.registerAlias(beanName, alias);
  15. }
  16. }
  17. }

  当调用BeanDefinitionReaderUtils向IOC容器注册解析的BeanDefinition时,真正完成注册功能的是DefaultListableBeanFactory。

2.1.17 向容器注册

  DefaultListableBeanFactory中 使 用 一 个HashMap的集合对象存放IOC容器中注册解析的BeanDefinition,向IOC容器注册的主要源码:

  1. //存储注册信息的BeanDefinition
  2. privatefinalMap<String,BeanDefinition> beanDefinitionMap =newConcurrentHashMap<>(256);
  3. //向Spring IOC容器注册解析的BeanDefinition
  4. @Override
  5. publicvoidregisterBeanDefinition(String beanName,BeanDefinition beanDefinition)
  6. throwsBeanDefinitionStoreException{
  7. Assert.hasText(beanName,"Bean name must not be empty");
  8. Assert.notNull(beanDefinition,"BeanDefinition must not be null");
  9. //检验解析的BeanDefinition
  10. if(beanDefinition instanceofAbstractBeanDefinition){
  11. try{
  12. ((AbstractBeanDefinition) beanDefinition).validate();
  13. }
  14. catch(BeanDefinitionValidationException ex){
  15. thrownewBeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
  16. "Validation of bean definition failed", ex);
  17. }
  18. }
  19. BeanDefinition existingDefinition =this.beanDefinitionMap.get(beanName);
  20. if(existingDefinition !=null){
  21. if(!isAllowBeanDefinitionOverriding()){
  22. thrownewBeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
  23. }
  24. elseif(existingDefinition.getRole()< beanDefinition.getRole()){
  25. if(logger.isInfoEnabled()){
  26. logger.info("Overriding user-defined bean definition for bean '"+ beanName +
  27. "' with a framework-generated bean definition: replacing ["+
  28. existingDefinition +"] with ["+ beanDefinition +"]");
  29. }
  30. }
  31. elseif(!beanDefinition.equals(existingDefinition)){
  32. if(logger.isDebugEnabled()){
  33. logger.debug("Overriding bean definition for bean '"+ beanName +
  34. "' with a different definition: replacing ["+ existingDefinition +
  35. "] with ["+ beanDefinition +"]");
  36. }
  37. }
  38. else{
  39. if(logger.isTraceEnabled()){
  40. logger.trace("Overriding bean definition for bean '"+ beanName +
  41. "' with an equivalent definition: replacing ["+ existingDefinition +
  42. "] with ["+ beanDefinition +"]");
  43. }
  44. }
  45. this.beanDefinitionMap.put(beanName, beanDefinition);
  46. }
  47. else{
  48. if(hasBeanCreationStarted()){
  49. //注册的过程中需要线程同步,以保证数据的一致性
  50. synchronized(this.beanDefinitionMap){
  51. this.beanDefinitionMap.put(beanName, beanDefinition);
  52. List<String> updatedDefinitions =newArrayList<>(this.beanDefinitionNames.size()+1);
  53. updatedDefinitions.addAll(this.beanDefinitionNames);
  54. updatedDefinitions.add(beanName);
  55. this.beanDefinitionNames = updatedDefinitions;
  56. removeManualSingletonName(beanName);
  57. }
  58. }
  59. else{
  60. this.beanDefinitionMap.put(beanName, beanDefinition);
  61. this.beanDefinitionNames.add(beanName);
  62. removeManualSingletonName(beanName);
  63. }
  64. this.frozenBeanDefinitionNames =null;
  65. }
  66. //检查是否已经注册过同名的BeanDefinition
  67. if(existingDefinition !=null||containsSingleton(beanName)){
  68. //重置所有已经注册过的BeanDefinition的缓存
  69. resetBeanDefinition(beanName);
  70. }
  71. }

  至此,Bean配置信息中配置的Bean被解析过后,已经注册到IOC容器中,被容器管理起来,真正完成了IOC容器初始化所做的全部工作。现在IOC容器中已经建立了整个Bean的配置信息,这些BeanDefinition 信息已经可以使用,并且可以被检索,IOC容器的作用就是对这些注册的Bean定义信息进行处理和维护。这些的注册的Bean定义信息是IOC容器控制反转的基础,正是有了这些注册的数据,容器才可以进行依赖注入。

2.2 IOC容器初始化流程小结

  Bean的注册流程:

  以上的这些过程都发生在AbstractApplicationContext的refresh方法中。

  AbstractApplicationContext的refresh方法逻辑:

  1)初始化前的准备工作,比如对系统属性或者环境变量进行准备及验证。

  2)初始化BeanFactory,并进行XML文件读取(component-scan->包括 class 文件)。

  3)对BeanFactory进行各种功能填充,比如@Qualifier和@Autowired。

  4)子类覆盖方法做额外的处理。

  5)激活各种BeanFactory处理器。

  6)注册拦截bean创建的bean处理器,这里只是注册,真正的调用是在getBean的时候。

  7)为上下文初始化Message源,即为不同语言的消息体进行国际化处理。

  8)初始化应用消息广播器,并放入 applicationEventMulticaster bean 中。

  9)留给子类来初始化其他的 bean。

  10)在所有注册的bean中查找listener bean,注册到消息广播器中。

  11)初始化剩下的代理实例(非 lazy-init)(bean 的加载)。

  12)完成刷新过程,通知生命周期处理器 lifecycleProcessor 刷新过程,同时发出ContextRefreshEvent 通知别人。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/241487?site
推荐阅读
相关标签
  

闽ICP备14008679号