赞
踩
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等 。
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的接口为:
- publicinterfaceApplicationContextextendsEnvironmentCapable,ListableBeanFactory,HierarchicalBeanFactory,
- MessageSource,ApplicationEventPublisher,ResourcePatternResolver{
-
- /*返回这个context的唯一id*/
- @Nullable
- StringgetId();
-
- /*返回这个context所属的应用名称*/
- StringgetApplicationName();
-
- /*返回一个context名称*/
- StringgetDisplayName();
-
- /*返回context加载的时间*/
- longgetStartupDate();
-
- /*返回父类context的上下文*/
- @Nullable
- ApplicationContextgetParent();
-
- /*公开AutowireCapableBeanFactory接口的能力给到context*/
- AutowireCapableBeanFactorygetAutowireCapableBeanFactory()throwsIllegalStateException;
ApplicationContext继承了HierachicalBeanFactory和ListableBeanFactory接口,在此基础上,还通过其他接口扩展了BeanFactory的功能。ApplicationContext初始化过程:
在获取ApplicationContext实例后,我们就可以像BeanFactory那样调用getBean(beanName)返回Bean了。ApplicationContext的初始化和BeanFactory初始化有一个重大区别:
BeanFactory在初始化容器时,并没有实例化Bean,直到第一次访问某个Bean时才实例化目标Bean。
ApplicationContext会在初始化应用上下文时就实例化所有单实例的Bean。
因此,ApplicationContext的初始化时间会比BeanFactory的时间稍微长一些。
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容器的初始化包括BeanDefinition的Resource定位、载入和注册这三个基本的过程。
ApplicationContext的继承体系:
ApplicationContext允许上下文嵌套,通过保持父上下文可以维持一个上下文体系。对于Bean的查找可以在这个上下文体系中发生,首先检查当前上下文,其次是父上下文,逐级向上,这样为不同的Spring应用提供了一个共享的Bean定义环境。
以常用的ClassPathXmlApplicationContext为例:
- ApplicationContext applicationContext =
- 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()方法。
通过分析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配置信息,也可以使用字符串数组,即下面两种方式都是可以的:
- ClassPathResource res =newClassPathResource("a.xml,b.xml");
- ClassPathResource res =newClassPathResource(newString[]{"a.xml","b.xml"});
至此,SpringIOC 容器在初始化时将配置的 Bean 配置信息定位为 Spring 封装的Resource。
Spring IOC容器对Bean配置资源的载入是从refresh()函数开始的,refresh()是一个模板方法,规定了IOC容器的启动流程,有些逻辑要交给其子类去实现。ClassPathXmlApplicationContext通过调用其父类 AbstractApplicationContext的refresh()函数,启动整个IOC容器对Bean定义的载入过程, AbstractApplicationContext中的refresh()中的逻辑处理:
- /**
- * refresh方法主要为IOC容器Bean的生命周期管理提供条件,在获取了BeanFactory之后都是
- * 在向该容器注册信息源和生命周期事件。
- * 在创建IOC容器前,如果已经有容器存在,需要把已有的容器销毁和关闭,
- * 以保证在refresh()方法之后使用的是新创建的IOC容器。
- */@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()){
- logger.warn("Exception encountered during context initialization - "+"cancelling refresh attempt: "+ ex);}
- //13、销毁已创建的 Bean
- destroyBeans();
- //14、取消refresh操作,重置容器的同步标识.
- cancelRefresh(ex);
- throw ex;}finally{//15、重设公共缓存 resetCommonCaches();}}}
refresh()方法主要为IOC容器Bean的生命周期管理提供条件,Spring IOC容器载入Bean配置信息,从其子类容器的refreshBeanFactory()方法启动 。
所以整个refresh()方法中 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();这句以后代码的都是注册容器的信息源和生命周期事件,我们前面说的载入就是从这句代码开始启动。
refresh()方法的主要作用是:在创建IOC容器前,如果已经有容器存在,则需要把已有的容器销毁和关闭,以保证在refresh之后使用的是新建立起来的IOC容器。
它类似于对IOC容器的重启,在新建立好的容器中对容器进行初始化,对Bean配置资源进行载入。
AbstractApplicationContext的obtainFreshBeanFactory()方法调用子类容器的 refreshBeanFactory()方法,启动容器载入Bean配置信息的过程:
- protectedConfigurableListableBeanFactoryobtainFreshBeanFactory(){//这里使用了委派设计模式,父类定义了抽象的refreshBeanFactory()方法,具体实现调用子类容器的 refreshBeanFactory()方法 refreshBeanFactory();ConfigurableListableBeanFactory beanFactory =getBeanFactory();if(logger.isDebugEnabled()){
- logger.debug("Bean factory for "+getDisplayName()+": "+ beanFactory);}return beanFactory;}
AbstractApplicationContext 类中只抽象定义了 refreshBeanFactory()方法,容器真正调用的是其子类AbstractRefreshableApplicationContext实现的 refreshBeanFactory()方法:
- protectedfinalvoidrefreshBeanFactory()throwsBeansException{//如果已经有容器,销毁容器中的 bean,关闭容器 if(hasBeanFactory()){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){thrownewApplicationContextException("I/O error parsing bean definition source for "+getDisplayName(), ex);}}
在这个方法(refreshBeanFactory)中,先判断BeanFactory是否存在,如果存在则先销毁beans并关闭beanFactory,接着创建DefaultListableBeanFactory,并调用loadBeanDefinitions(beanFactory)装载bean定义。
AbstractRefreshableApplicationContext中只定义了抽象的loadBeanDefinitions方法,容器真正调用的是其子类AbstractXmlApplicationContext对该方法的实现:
- publicabstractclassAbstractXmlApplicationContextextendsAbstractRefreshableConfigApplicationContext{...//实现父类抽象的载入 Bean 定义方法 @OverrideprotectedvoidloadBeanDefinitions(DefaultListableBeanFactory beanFactory)throwsBeansException,IOException{//创建 XmlBeanDefinitionReader,即创建Bean读取器,并通过回调设置到容器中去,容器使用该读取器读取Bean配置资源 XmlBeanDefinitionReader beanDefinitionReader =newXmlBeanDefinitionReader(beanFactory);//为Bean读取器设置Spring资源加载器,AbstractXmlApplicationContext的 //祖先父类AbstractApplicationContext继承DefaultResourceLoader,因此,容器本身也是一个资源加载器
- beanDefinitionReader.setEnvironment(this.getEnvironment());
- beanDefinitionReader.setResourceLoader(this);//为Bean读取器设置SAX xml解析器
- beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));//当Bean读取器读取Bean定义的Xml资源文件时,启用Xml的校验机制 initBeanDefinitionReader(beanDefinitionReader);//Bean读取器真正实现加载的方法 loadBeanDefinitions(beanDefinitionReader);}protectedvoidinitBeanDefinitionReader(XmlBeanDefinitionReader reader){
- reader.setValidating(this.validating);}//Xml Bean读取器加载Bean配置资源 protectedvoidloadBeanDefinitions(XmlBeanDefinitionReader reader)throwsBeansException,IOException{//获取Bean配置资源的定位 Resource[] configResources =getConfigResources();if(configResources !=null){//Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位的Bean配置资源
- reader.loadBeanDefinitions(configResources);}// 如果子类中获取的Bean配置资源定位为空,则获取ClassPathXmlApplicationContext // 构造方法中setConfigLocations方法设置的资源 String[] configLocations =getConfigLocations();if(configLocations !=null){
- //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位
- //的Bean配置资源
- reader.loadBeanDefinitions(configLocations);}}//这里又使用了一个委托模式,调用子类的获取Bean配置资源定位的方法 //该方法在ClassPathXmlApplicationContext中进行实现,对于我们 //举例分析源码的ClassPathXmlApplicationContext没有使用该方法 @NullableprotectedResource[]getConfigResources(){returnnull;}}
以 XmlBean 读取器的其中一种策略 XmlBeanDefinitionReader为例。XmlBeanDefinitionReader 调用其父类AbstractBeanDefinitionReader的reader.loadBeanDefinitions()方法读取Bean配置资源。
由于我们使用ClassPathXmlApplicationContext作为例子分析,因此getConfigResources的返回值为null,因此程序执行reader.loadBeanDefinitions(configLocations)分支。
在XmlBeanDefinitionReader的抽象父类AbstractBeanDefinitionReader中定义了载入过程。AbstractBeanDefinitionReader的loadBeanDefinitions()方法:
- //重载方法,调用下面的 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){
- actualResources.add(resource);}}if(logger.isDebugEnabled()){
- 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){
- actualResources.add(resource);}if(logger.isDebugEnabled()){
- 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){
- 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中来。
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()方法:
- @OverrideprotectedResourcegetResourceByPath(String path){if(path.startsWith("/")){
- path = path.substring(1);}//这里使用文件系统资源对象来定义bean文件 returnnewFileSystemResource(path);}
通过子类的覆盖,巧妙地完成了将类路径变为文件路径的转换。
继续回到XmlBeanDefinitionReader的loadBeanDefinitions(Resource …)方法看到代表bean文件的资源定义以后的载入过程。
- //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){
- inputSource.setEncoding(encodedResource.getEncoding());}//这里是具体的读取过程 returndoLoadBeanDefinitions(inputSource, encodedResource.getResource());}finally{//关闭从Resource中得到的IO流
- 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);}...}
-
- protectedDocumentdoLoadDocument(InputSource inputSource,Resource resource)throwsException{
- returnthis.documentLoader.loadDocument(inputSource,getEntityResolver(),this.errorHandler,
- getValidationModeForResource(resource),isNamespaceAware());
- }
通过源码分析,载入Bean配置信息的最后一步是将Bean配置信息转换为Document对象,该过程由doLoadDocument()方法实现。
将Bean配置资源转换成Document对象的代码,是在DefaultDocumentLoader中:
- //使用标准的JAXP将载入的Bean配置资源转换成document对象 @OverridepublicDocumentloadDocument(InputSource inputSource,EntityResolver entityResolver,ErrorHandler errorHandler,int validationMode,boolean namespaceAware)throwsException{//创建文件解析器工厂 DocumentBuilderFactory factory =createDocumentBuilderFactory(validationMode, namespaceAware);if(logger.isDebugEnabled()){
- 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();
- factory.setNamespaceAware(namespaceAware);//设置解析XML的校验 if(validationMode !=XmlValidationModeDetector.VALIDATION_NONE){
- factory.setValidating(true);if(validationMode ==XmlValidationModeDetector.VALIDATION_XSD){
- factory.setNamespaceAware(true);try{
- 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.");
- pcex.initCause(ex);throw pcex;}}}return factory;}
至此Spring IOC容器根据定位的Bean配置信息,将其加载读入并转换成为Document对象过程完成。
接下来我们要继续分析Spring IOC容器将载入的Bean配置信息转换为Document对象之后,是如何将其解析为Spring IOC管理的Bean对象并将其注册到容器中的。
XmlBeanDefinitionReader类中的doLoadBeanDefinition()方法,是从特定XML文件中实际载入Bean配置资源的方法,该方法在载入Bean配置资源之后将其转换为Document对象。
接下来调用registerBeanDefinitions()启动Spring IOC容器对Bean定义的解析过程:
- //从特定XML文件中实际载入Bean配置资源的方法
- protectedintdoLoadBeanDefinitions(InputSource inputSource,Resource resource)
- throwsBeanDefinitionStoreException{
-
- try{
- // 将XML文件转换为DOM对象,解析过程由documentLoader方法实现
- Document doc =doLoadDocument(inputSource, resource);
- // 启动对Bean定义解析的详细过程,该解析过程会用到Spring的Bean配置规则
- int count =registerBeanDefinitions(doc, resource);
- if(logger.isDebugEnabled()){
- logger.debug("Loaded "+ count +" bean definitions from "+ resource);
- }
- return count;
- }
- catch(BeanDefinitionStoreException ex){
- throw ex;
- }
- catch(SAXParseException ex){
- thrownewXmlBeanDefinitionStoreException(resource.getDescription(),
- "Line "+ ex.getLineNumber()+" in XML document from "+ resource +" is invalid", ex);
- }
- catch(SAXException ex){
- thrownewXmlBeanDefinitionStoreException(resource.getDescription(),
- "XML document from "+ resource +" is invalid", ex);
- }
- catch(ParserConfigurationException ex){
- thrownewBeanDefinitionStoreException(resource.getDescription(),
- "Parser configuration exception parsing XML from "+ resource, ex);
- }
- catch(IOException ex){
- thrownewBeanDefinitionStoreException(resource.getDescription(),
- "IOException parsing XML document from "+ resource, ex);
- }
- catch(Throwable ex){
- thrownewBeanDefinitionStoreException(resource.getDescription(),
- "Unexpected exception parsing XML document from "+ resource, ex);
- }
- }//按照Spring的Bean语义要求,将Bean配置资源解析并转换为容器内部数据结构 publicintregisterBeanDefinitions(Document doc,Resource resource)throwsBeanDefinitionStoreException{//得到BeanDefinitionDocumentReader来对xml格式的BeanDefinition解析 BeanDefinitionDocumentReader documentReader =createBeanDefinitionDocumentReader();//获得容器中注册的Bean数量 int countBefore =getRegistry().getBeanDefinitionCount();//解析过程入口,这里使用了委派模式,BeanDefinitionDocumentReader只是个接口, //具体的解析实现过程有实现类DefaultBeanDefinitionDocumentReader完成
- documentReader.registerBeanDefinitions(doc,createReaderContext(resource));//统计解析的Bean数量 returngetRegistry().getBeanDefinitionCount()- countBefore;}
Bean配置资源的载入解析分为以下两个过程:
通过调用XML解析器将Bean配置信息转换得到Document对象,但是这些Document对象并没有按照Spring 的Bean规则进行解析。这一步是载入的过程 。
在完成通用的XML解析之后,按照Spring Bean的定义规则对Document对象进行解析,其解析过程是在接口BeanDefinitionDocumentReader的实现类DefaultBeanDefinitionDocumentReader 中实现。
BeanDefinitionDocumentReader接口通过registerBeanDefinitions()方法,调用其实现类DefaultBeanDefinitionDocumentReader对Document对象进行解析:
- //根据Spring DTD对Bean的定义规则解析Bean定义Document对象
- @Override
- publicvoidregisterBeanDefinitions(Document doc,XmlReaderContext readerContext){
- //获得XML描述符
- this.readerContext = readerContext;
- //获取document的根元素
- doRegisterBeanDefinitions(doc.getDocumentElement());
- }
-
- @SuppressWarnings("deprecation")
- protectedvoiddoRegisterBeanDefinitions(Element root){
- // 具体的解析过程由BeanDefinitionParserDelegate实现,其中定义了Spring Bean定义XML文件的各种元素
- BeanDefinitionParserDelegate parent =this.delegate;
- this.delegate =createDelegate(getReaderContext(), root, parent);
-
- if(this.delegate.isDefaultNamespace(root)){
- //处理profile属性
- String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
- if(StringUtils.hasText(profileSpec)){
- String[] specifiedProfiles =StringUtils.tokenizeToStringArray(
- profileSpec,BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
- if(!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)){
- if(logger.isDebugEnabled()){
- logger.debug("Skipped XML bean definition file due to specified profiles ["+ profileSpec +
- "] not matching: "+getReaderContext().getResource());
- }
- return;
- }
- }
- }
-
- //在解析Bean定义之前,进行自定义解析,增强解析过程的可扩展性
- preProcessXml(root);
- //从文档的根元素开始进行Bean定义的文档对象的解析
- parseBeanDefinitions(root,this.delegate);
- //在解析Bean定义之后,进行自定义解析,增加解析过程的可扩展性
- postProcessXml(root);
-
- this.delegate = parent;
- }
-
- //创建BeanDefinitionParserDelegate,用于完成真正的解析过程
- protectedBeanDefinitionParserDelegatecreateDelegate(
- XmlReaderContext readerContext,Element root,@NullableBeanDefinitionParserDelegate parentDelegate){
-
- BeanDefinitionParserDelegate delegate =newBeanDefinitionParserDelegate(readerContext);
- //BeanDefinitionParserDelegate初始化document根元素
- delegate.initDefaults(root, parentDelegate);
- return delegate;
- }
-
- //使用Spring的Bean规则从文档的根元素开始Bean定义的文档对象的解析
- protectedvoidparseBeanDefinitions(Element root,BeanDefinitionParserDelegate delegate){
- //Bean定义的文档对象使用了Spring默认的XML命名空间
- if(delegate.isDefaultNamespace(root)){
- //获取Bean定义的文档对象根元素的所有子节点
- NodeList nl = root.getChildNodes();
- for(int i =0; i < nl.getLength(); i++){
- Node node = nl.item(i);
- //获取的文档节点是XML元素节点
- if(node instanceofElement){
- Element ele =(Element) node;
- //对bean的处理
- if(delegate.isDefaultNamespace(ele)){
- //使用Spring的Bean规则解析元素节点
- parseDefaultElement(ele, delegate);
- }else{
- //如果没有使用Spring默认的XML命名空间,则使用用户自定义的解析规则解析元素节点
- delegate.parseCustomElement(ele);
- }
- }
- }
- }else{
- //Document的根节点没有使用Spring默认的命名空间,使用自定义的解析规则解析Document的根节点
- delegate.parseCustomElement(root);
- }
- }
-
- //使用Spring的Bean规则解析文档元素节点
- privatevoidparseDefaultElement(Element ele,BeanDefinitionParserDelegate delegate){
- //如果元素节点是<Import>导入元素,进行导入解析
- if(delegate.nodeNameEquals(ele, IMPORT_ELEMENT)){
- importBeanDefinitionResource(ele);
- }
- //如果元素节点是<Alias>导入元素,进行别名解析
- elseif(delegate.nodeNameEquals(ele, ALIAS_ELEMENT)){
- processAliasRegistration(ele);
- }
- //如果元素节点是<Bean>导入元素,按照Spring的Bean规则解析元素
- elseif(delegate.nodeNameEquals(ele, BEAN_ELEMENT)){
- processBeanDefinition(ele, delegate);
- }
- elseif(delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)){
- doRegisterBeanDefinitions(ele);
- }
- }
-
- //解析<import>导入元素,从给定的导入路径加载Bean资源到Spring IOC容器中
- protectedvoidimportBeanDefinitionResource(Element ele){
- //获取给定的导入元素的location属性
- String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
- //如果导入元素的location属性为空,则没有导入任何资源,直接返回
- if(!StringUtils.hasText(location)){
- getReaderContext().error("Resource location must not be empty", ele);
- return;
- }
-
- //使用系统变量值解析location属性值
- location =getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
-
- Set<Resource> actualResources =newLinkedHashSet<>(4);
-
- //标识给定的导入元素的location属性值是否是绝对路径
- boolean absoluteLocation =false;
- try{
- absoluteLocation =ResourcePatternUtils.isUrl(location)||ResourceUtils.toURI(location).isAbsolute();
- }catch(URISyntaxException ex){
- }
-
- // 给定的导入元素的location属性值是绝对路径
- if(absoluteLocation){
- try{
- //使用资源读入器加载给定路径的Bean资源
- int importCount =getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
- if(logger.isTraceEnabled()){
- logger.trace("Imported "+ importCount +" bean definitions from URL location ["+ location +"]");
- }
- }catch(BeanDefinitionStoreException ex){
- getReaderContext().error(
- "Failed to import bean definitions from URL location ["+ location +"]", ele, ex);
- }
- }else{
- // 给定的导入元素的location属性值是相对路径
- try{
- int importCount;
- //将给定导入元素的location封装为相对路径
- Resource relativeResource =getReaderContext().getResource().createRelative(location);
- if(relativeResource.exists()){
- //使用资源读入器加载Bean资源
- importCount =getReaderContext().getReader().loadBeanDefinitions(relativeResource);
- actualResources.add(relativeResource);
- }
- //封装的相对路径资源不存在
- else{
- //获取Spring IOC容器资源读入器的基本路径
- String baseLocation =getReaderContext().getResource().getURL().toString();
- //根据Spring IOC容器资源读入器的基本路径加载给定导入路径的资源
- importCount =getReaderContext().getReader().loadBeanDefinitions(
- StringUtils.applyRelativePath(baseLocation, location), actualResources);
- }
- if(logger.isTraceEnabled()){
- logger.trace("Imported "+ importCount +" bean definitions from relative location ["+ location +"]");
- }
- }catch(IOException ex){
- getReaderContext().error("Failed to resolve current resource location", ele, ex);
- }catch(BeanDefinitionStoreException ex){
- getReaderContext().error(
- "Failed to import bean definitions from relative location ["+ location +"]", ele, ex);
- }
- }
- Resource[] actResArray = actualResources.toArray(newResource[0]);
- //在解析完import元素之后,发送容器导入其他资源处理完成事件
- getReaderContext().fireImportProcessed(location, actResArray,extractSource(ele));
- }
-
- //解析alias别名元素,为Bean向IOC容器注册别名
- protectedvoidprocessAliasRegistration(Element ele){
- //获取<alias>别名元素中name的属性值
- String name = ele.getAttribute(NAME_ATTRIBUTE);
- //获取<alias>别名元素中alias的属性值
- String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
- boolean valid =true;
- //别名元素的name属性值为空
- if(!StringUtils.hasText(name)){
- getReaderContext().error("Name must not be empty", ele);
- valid =false;
- }
- //alias别名元素的alias属性值为空
- if(!StringUtils.hasText(alias)){
- getReaderContext().error("Alias must not be empty", ele);
- valid =false;
- }
- if(valid){
- try{
- //向容器的资源读入器注册别名
- getReaderContext().getRegistry().registerAlias(name, alias);
- }catch(Exception ex){
- getReaderContext().error("Failed to register alias '"+ alias +
- "' for bean with name '"+ name +"'", ele, ex);
- }
- //在解析完成<alias>元素之后,发送容器别名处理完成事件
- getReaderContext().fireAliasRegistered(name, alias,extractSource(ele));
- }
- }
-
- //解析Bean资源文档对象的普通元素
- protectedvoidprocessBeanDefinition(Element ele,BeanDefinitionParserDelegate delegate){
- BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
- //BeanDefinitionHolder是对BeanDefinition的封装,即Bean定义的封装类
- //对文档对象中bean元素的解析由BeanDefinitionParserDelegate实现
- if(bdHolder !=null){
- bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
- try{
- //向Spring IOC容器注册解析得到的Bean定义,这是Bean定义向IOC容器注册的入口
- BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder,getReaderContext().getRegistry());
- }catch(BeanDefinitionStoreException ex){
- getReaderContext().error("Failed to register bean definition with name '"+
- bdHolder.getBeanName()+"'", ele, ex);
- }
- //在完成向Spring IOC容器注册解析得到的Bean定义之后,发送注册事件
- getReaderContext().fireComponentRegistered(newBeanComponentDefinition(bdHolder));
- }
- }
我们使用Spring时,在Spring配置文件中可以使用<import>元素来导入IOC容器所需要的其他资源,Spring IOC容器在解析时会首先将指定导入的资源加载进容器中。
使用<ailas>别名时,Spring IOC容器首先将别名元素所定义的别名注册到容器中。
对于既不是<import>元素,又不是<alias>元素的元素,即Spring配置文件中普通的<bean>元素的解析由BeanDefinitionParserDelegate类的parseBeanDefinitionElement()方法来实现。
Bean 配置信息中的<import>和<alias>元素解析在DefaultBeanDefinitionDocumentReader 中已经完成,对Bean配置信息中使用最多的<bean>元素交由BeanDefinitionParserDelegate来解析:
- //解析<bean>元素的入口
- @Nullable
- publicBeanDefinitionHolderparseBeanDefinitionElement(Element ele){
- returnparseBeanDefinitionElement(ele,null);
- }
-
- //解析Bean配置信息中的<bean>元素,这个方法中主要处理bean中的id,name和别名属性
- @Nullable
- publicBeanDefinitionHolderparseBeanDefinitionElement(Element ele,@NullableBeanDefinition containingBean){
- //获取<Bean>元素中的id属性值
- String id = ele.getAttribute(ID_ATTRIBUTE);
- //获取<Bean>元素中的name属性值
- String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
-
- //获取<Bean>元素中的alias属性值
- List<String> aliases =newArrayList<>();
- if(StringUtils.hasLength(nameAttr)){
- String[] nameArr =StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
- aliases.addAll(Arrays.asList(nameArr));
- }
-
- String beanName = id;
- //如果<bean>元素中没有配置id属性,将别名中的第一个值赋值给beanName
- if(!StringUtils.hasText(beanName)&&!aliases.isEmpty()){
- beanName = aliases.remove(0);
- if(logger.isTraceEnabled()){
- logger.trace("No XML 'id' specified - using '"+ beanName +
- "' as bean name and "+ aliases +" as aliases");
- }
- }
-
- //检查<bean>元素所配置的id和name的唯一性,containingBean标识<bean>元素中是否包含子<bean>元素
- if(containingBean ==null){
- //检查<bean>元素所排位置的id,name,或者别名是否重复
- checkNameUniqueness(beanName, aliases, ele);
- }
-
- //详细对<bean>元素中配置的Bean定义进行解析
- AbstractBeanDefinition beanDefinition =parseBeanDefinitionElement(ele, beanName, containingBean);
- if(beanDefinition !=null){
- if(!StringUtils.hasText(beanName)){
- try{
- //如果不存在id,name,alias属性,且没有包含子元素,那么
- //根据spring中提供的命名规则为当前bean生成对应的beanName
- if(containingBean !=null){
- beanName =BeanDefinitionReaderUtils.generateBeanName(
- beanDefinition,this.readerContext.getRegistry(),true);
- }
- else{
- //如果bean元素中没有配置id,name,alias,且包含了子元素,则
- //将解析的Bean使用别名向IOC容器注册
- beanName =this.readerContext.generateBeanName(beanDefinition);
- //为解析的Bean使用别名注册时,为了向后兼容Spring1.2/2.0,给别名添加类名后缀
- String beanClassName = beanDefinition.getBeanClassName();
- if(beanClassName !=null&&
- beanName.startsWith(beanClassName)&& beanName.length()> beanClassName.length()&&
- !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)){
- aliases.add(beanClassName);
- }
- }
- if(logger.isTraceEnabled()){
- logger.trace("Neither XML 'id' nor 'name' specified - "+
- "using generated bean name ["+ beanName +"]");
- }
- }
- catch(Exception ex){
- error(ex.getMessage(), ele);
- returnnull;
- }
- }
- String[] aliasesArray =StringUtils.toStringArray(aliases);
- returnnewBeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
- }
- //当解析出错的时候,返回null
- returnnull;
- }
-
- protectedvoidcheckNameUniqueness(String beanName,List<String> aliases,Element beanElement){
- String foundName =null;
-
- if(StringUtils.hasText(beanName)&&this.usedNames.contains(beanName)){
- foundName = beanName;
- }
- if(foundName ==null){
- foundName =CollectionUtils.findFirstMatch(this.usedNames, aliases);
- }
- if(foundName !=null){
- error("Bean name '"+ foundName +"' is already used in this <beans> element", beanElement);
- }
-
- this.usedNames.add(beanName);
- this.usedNames.addAll(aliases);
- }
-
- //详细对bean元素中配置的bean定义的其他属性进行解析,主要处理id,name,alias的其他属性
- @Nullable
- publicAbstractBeanDefinitionparseBeanDefinitionElement(
- Element ele,String beanName,@NullableBeanDefinition containingBean){
-
- //记录解析的bean元素
- this.parseState.push(newBeanEntry(beanName));
-
- //只读取bean元素中配置的class名字,然后载入BeanDefinition中,只是记录配置
- //的class名字,不做实例化,对象的实例化在依赖注入时完成
- String className =null;
- //解析class属性
- if(ele.hasAttribute(CLASS_ATTRIBUTE)){
- className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
- }
- String parent =null;
- //解析parent属性
- if(ele.hasAttribute(PARENT_ATTRIBUTE)){
- parent = ele.getAttribute(PARENT_ATTRIBUTE);
- }
-
- try{
- //创建用于承载属性的AbstractBeanDefinition类型的GenericBeanDefinition,为载入Bean定义信息做准备
- AbstractBeanDefinition bd =createBeanDefinition(className, parent);
-
- //对bean元素中配置的一些属性进行解析和设置,如是否单例
- parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
- //为bean元素解析的bean设置描述信息
- bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
-
- //对<Bean>元素的meta(元信息)属性解析
- parseMetaElements(ele, bd);
- //对<Bean>元素的lookup-method属性解析
- parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
- //对<Bean>元素的replaced-method属性解析
- parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
-
- //解析构造函数参数
- parseConstructorArgElements(ele, bd);
- //解析<property>元素
- parsePropertyElements(ele, bd);
- //解析<qualifier>元素
- parseQualifierElements(ele, bd);
-
- //为当前解析的bean设置所需的资源和依赖对象
- bd.setResource(this.readerContext.getResource());
- bd.setSource(extractSource(ele));
-
- return bd;
- }
- catch(ClassNotFoundException ex){
- error("Bean class ["+ className +"] not found", ele, ex);
- }
- catch(NoClassDefFoundError err){
- error("Class that bean class ["+ className +"] depends on not found", ele, err);
- }
- catch(Throwable ex){
- error("Unexpected failure during bean definition parsing", ele, ex);
- }
- finally{
- this.parseState.pop();
- }
- //当解析bean元素出错时,返回null
- returnnull;
- }
通过对上述源码的分析,就会明白我们在Spring配置文件中<Bean>元素的中配置的属性就是通过该方法解析和设置到Bean中去的。
在解析<Bean>元素过程中没有创建和实例化Bean对象,只是创建了Bean对象的定义类BeanDefinition,将<Bean>元素中的配置信息设置到BeanDefinition中作为记录,当依赖注入时才使用这些记录信息创建和实例化具体的Bean对象。
BeanDefinitionParserDelegate在解析<Bean>调用parsePropertyElements()方法解析<Bean>元素中的<property>属性子元素:
- /**
- * 解析<bean>元素中所有的<property>子元素
- */
- publicvoidparsePropertyElements(Element beanEle,BeanDefinition bd){
- //获取<bean>元素的所有子元素
- NodeList nl = beanEle.getChildNodes();
- for(int i =0; i < nl.getLength(); i++){
- Node node = nl.item(i);
- //如果子元素是<property>子元素,则调用下面方法进行<property>子元素解析
- if(isCandidateElement(node)&&nodeNameEquals(node, PROPERTY_ELEMENT)){
- parsePropertyElement((Element) node, bd);
- }
- }
- }
-
- //解析<property>元素
- publicvoidparsePropertyElement(Element ele,BeanDefinition bd){
- //获取<property>元素的名字
- String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
- if(!StringUtils.hasLength(propertyName)){
- error("Tag 'property' must have a 'name' attribute", ele);
- return;
- }
- this.parseState.push(newPropertyEntry(propertyName));
- try{
- //如果一个bean中已经有同名的property属性存在则不进行解析,直接返回,
- //即如果配置了多个同名的属性则第一个起作用
- if(bd.getPropertyValues().contains(propertyName)){
- error("Multiple 'property' definitions for property '"+ propertyName +"'", ele);
- return;
- }
- //解析获取property元素的值
- Object val =parsePropertyValue(ele, bd, propertyName);
- //根据property元素的名字和值创建实例
- PropertyValue pv =newPropertyValue(propertyName, val);
- //解析<property>元素的属性
- parseMetaElements(ele, pv);
- pv.setSource(extractSource(ele));
- bd.getPropertyValues().addPropertyValue(pv);
- }
- finally{
- this.parseState.pop();
- }
- }
-
- //解析获取property元素的值
- @Nullable
- publicObjectparsePropertyValue(Element ele,BeanDefinition bd,@NullableString propertyName){
- String elementName =(propertyName !=null?
- "<property> element for property '"+ propertyName +"'":
- "<constructor-arg> element");
-
- // Should only have one child element: , etc.
- //获取<property>的所有子元素,只能是其中一种类型:ref, value, list等
- NodeList nl = ele.getChildNodes();
- Element subElement =null;
- for(int i =0; i < nl.getLength(); i++){
- Node node = nl.item(i);
- //子元素不是description和meta属性
- if(node instanceofElement&&!nodeNameEquals(node, DESCRIPTION_ELEMENT)&&
- !nodeNameEquals(node, META_ELEMENT)){
- if(subElement !=null){
- error(elementName +" must not contain more than one sub-element", ele);
- }
- else{
- //当前property元素包含子元素
- subElement =(Element) node;
- }
- }
- }
-
- //判断属性值是ref还是value,不允许既是ref又是value
- boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
- boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
- if((hasRefAttribute && hasValueAttribute)||
- ((hasRefAttribute || hasValueAttribute)&& subElement !=null)){
- error(elementName +
- " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
- }
-
- //如果属性值是ref,创建一个ref的数据对象RuntimeBeanReference
- //这个对象封装了ref信息
- if(hasRefAttribute){
- String refName = ele.getAttribute(REF_ATTRIBUTE);
- if(!StringUtils.hasText(refName)){
- error(elementName +" contains empty 'ref' attribute", ele);
- }
- //一个指向运行时所依赖对象的引用
- RuntimeBeanReference ref =newRuntimeBeanReference(refName);
- //设置这个ref的数据对象被当前对象所引用
- ref.setSource(extractSource(ele));
- return ref;
- }
- //如果属性值是value,创建一个value的数据对象TypedStringValue
- //这个对象封装了value信息
- elseif(hasValueAttribute){
- //一个持有Strig类型值的对象
- TypedStringValue valueHolder =newTypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
- //设置这个value的数据对象被当前对象所引用
- valueHolder.setSource(extractSource(ele));
- return valueHolder;
- }
- //如果当前property元素还有子元素
- elseif(subElement !=null){
- //解析<property>的子元素
- returnparsePropertySubElement(subElement, bd);
- }
- else{
- //属性值既不是ref也不是value,解析出错,返回null
- error(elementName +" must specify a ref or value", ele);
- returnnull;
- }
- }
在Spring配置文件中,<Bean>元素中<property>元素的相关配置是如何处理的:
ref被封装为指向依赖对象一个引用。
value配置都会封装成一个字符串类型的对象。
ref和value都通过“解析的数据类型属性值.setSource(extractSource(ele));”方法将属性值/引用与所引用的属性关联起来。
在方法的最后对于<property>元素的子元素通过parsePropertySubElement ()方法解析,我们继续分析该方法的源码,了解其解析过程。
在BeanDefinitionParserDelegate类中的parsePropertySubElement()方法对<property>中的子元素解析:
- //解析property元素中的ref、value或者集合等子元素
- @Nullable
- publicObjectparsePropertySubElement(Element ele,@NullableBeanDefinition bd,@NullableString defaultValueType){
- //如果<property>元素没有使用Spring默认的命名空间,则使用用户自定义的规则解析内嵌元素
- if(!isDefaultNamespace(ele)){
- returnparseNestedCustomElement(ele, bd);
- }
- //如果子元素是bean,则使用解析bean元素的方法解析
- elseif(nodeNameEquals(ele, BEAN_ELEMENT)){
- BeanDefinitionHolder nestedBd =parseBeanDefinitionElement(ele, bd);
- if(nestedBd !=null){
- nestedBd =decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
- }
- return nestedBd;
- }
- //如果子元素的ref,ref只能有三个属性,bean,local,parent
- elseif(nodeNameEquals(ele, REF_ELEMENT)){
- // A generic reference to any name of any bean.
- String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);
- boolean toParent =false;
- if(!StringUtils.hasLength(refName)){
- //获取property元素的parent属性值,引用父容器中的Bean
- refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);
- toParent =true;
- if(!StringUtils.hasLength(refName)){
- error("'bean' or 'parent' is required for <ref> element", ele);
- returnnull;
- }
- }
- if(!StringUtils.hasText(refName)){
- error("<ref> element contains empty target attribute", ele);
- returnnull;
- }
- //创建ref类型数据,指向被引用的对象
- RuntimeBeanReference ref =newRuntimeBeanReference(refName, toParent);
- //设置引用类型值被当前子元素所引用
- ref.setSource(extractSource(ele));
- return ref;
- }
- //如果子元素是<idref>,使用解析ref元素的方法解析
- elseif(nodeNameEquals(ele, IDREF_ELEMENT)){
- returnparseIdRefElement(ele);
- }
- //如果子元素是<value>,则使用解析value元素的方法解析
- elseif(nodeNameEquals(ele, VALUE_ELEMENT)){
- returnparseValueElement(ele, defaultValueType);
- }
- //如果子元素是null,为property元素设置一个封装null值的字符串数据
- elseif(nodeNameEquals(ele, NULL_ELEMENT)){
- TypedStringValue nullHolder =newTypedStringValue(null);
- nullHolder.setSource(extractSource(ele));
- return nullHolder;
- }
- //如果子元素是<array>,使用解析array集合子元素的方法解析
- elseif(nodeNameEquals(ele, ARRAY_ELEMENT)){
- returnparseArrayElement(ele, bd);
- }
- //如果子元素是<list>,使用解析list集合子元素的方法解析
- elseif(nodeNameEquals(ele, LIST_ELEMENT)){
- returnparseListElement(ele, bd);
- }
- //如果子元素是<set>,使用解析set集合子元素的方法解析
- elseif(nodeNameEquals(ele, SET_ELEMENT)){
- returnparseSetElement(ele, bd);
- }
- //如果子元素是<map>,使用解析map集合子元素的方法解析
- elseif(nodeNameEquals(ele, MAP_ELEMENT)){
- returnparseMapElement(ele, bd);
- }
- //如果子元素是<props>,使用解析props集合子元素的方法解析
- elseif(nodeNameEquals(ele, PROPS_ELEMENT)){
- returnparsePropsElement(ele);
- }
- //既不是ref,又不是value,也不是集合,则子元素配置错误,返回null
- else{
- error("Unknown property sub-element: ["+ ele.getNodeName()+"]", ele);
- returnnull;
- }
- }
在Spring配置文件中,对<property>元素中配置的array、list、set、map、prop等各种集合子元素的都通过上述方法解析,生成对应的数据对象,比如ManagedList、 ManagedArray、ManagedSet 等,这些Managed类是Spring对象BeanDefiniton的数据封装,对集合数据类型的具体解析有各自的解析方法实现,解析方法的命名非常规范,一目了然,我们对<list>集合元素的解析方法进行源码分析,了解其实现过程。
在BeanDefinitionParserDelegate类中的parseListElement()方法就是具体实现解析<property>元素中的<list>集合子元素:
- //解析<list>集合子元素
- publicList<Object>parseListElement(Element collectionEle,@NullableBeanDefinition bd){
- //获取<list>元素的value-type属性,即获取集合元素的数据类型
- String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
- //获取<list>集合子元素中的所有子节点
- NodeList nl = collectionEle.getChildNodes();
- //Spring将list封装成ManagedList对象
- ManagedList<Object> target =newManagedList<>(nl.getLength());
- target.setSource(extractSource(collectionEle));
- //设置集合目标数据类型
- target.setElementTypeName(defaultElementType);
- target.setMergeEnabled(parseMergeAttribute(collectionEle));
- //具体的<list>元素解析
- parseCollectionElements(nl, target, bd, defaultElementType);
- return target;
- }
-
- //具体解析list集合子元素,<array>,<list>,<set>都用该方法解析
- protectedvoidparseCollectionElements(
- NodeList elementNodes,Collection<Object> target,@NullableBeanDefinition bd,String defaultElementType){
-
- //遍历集合的所有节点
- for(int i =0; i < elementNodes.getLength(); i++){
- Node node = elementNodes.item(i);
- //节点不是description节点
- if(node instanceofElement&&!nodeNameEquals(node, DESCRIPTION_ELEMENT)){
- //将解析的元素加入集合,递归调用下一个子元素
- target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
- }
- }
- }
经过对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容器的初始化过程。
接下来我们来分析DefaultBeanDefinitionDocumentReader对Bean定义转换的Document对象解析的流程中, 在其parseDefaultElement() 方法中完成对Document对象的解析后得到封装BeanDefinition的BeanDefinitionHold对象 , 然后调用BeanDefinitionReaderUtils的registerBeanDefinition()方向IOC容器注册解析的Bean:
- //将解析的BeanDefinitionHold 注册到容器中
- publicstaticvoidregisterBeanDefinition(
- BeanDefinitionHolder definitionHolder,BeanDefinitionRegistry registry)
- throwsBeanDefinitionStoreException{
-
- //获取解析的BeanDefinition的名称
- String beanName = definitionHolder.getBeanName();
- //向Spring IOC容器注册BeanDefinition
- registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
-
- // Register aliases for bean name, if any.
- // 如果解析的BeanDefinition有别名,向Spring IOC容器注册别名
- String[] aliases = definitionHolder.getAliases();
- if(aliases !=null){
- for(String alias : aliases){
- registry.registerAlias(beanName, alias);
- }
- }
- }
当调用BeanDefinitionReaderUtils向IOC容器注册解析的BeanDefinition时,真正完成注册功能的是DefaultListableBeanFactory。
DefaultListableBeanFactory中 使 用 一 个HashMap的集合对象存放IOC容器中注册解析的BeanDefinition,向IOC容器注册的主要源码:
- //存储注册信息的BeanDefinition
- privatefinalMap<String,BeanDefinition> beanDefinitionMap =newConcurrentHashMap<>(256);
-
- //向Spring IOC容器注册解析的BeanDefinition
- @Override
- publicvoidregisterBeanDefinition(String beanName,BeanDefinition beanDefinition)
- throwsBeanDefinitionStoreException{
-
- Assert.hasText(beanName,"Bean name must not be empty");
- Assert.notNull(beanDefinition,"BeanDefinition must not be null");
-
- //检验解析的BeanDefinition
- if(beanDefinition instanceofAbstractBeanDefinition){
- try{
- ((AbstractBeanDefinition) beanDefinition).validate();
- }
- catch(BeanDefinitionValidationException ex){
- thrownewBeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
- "Validation of bean definition failed", ex);
- }
- }
-
- BeanDefinition existingDefinition =this.beanDefinitionMap.get(beanName);
- if(existingDefinition !=null){
- if(!isAllowBeanDefinitionOverriding()){
- thrownewBeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
- }
- elseif(existingDefinition.getRole()< beanDefinition.getRole()){
- if(logger.isInfoEnabled()){
- logger.info("Overriding user-defined bean definition for bean '"+ beanName +
- "' with a framework-generated bean definition: replacing ["+
- existingDefinition +"] with ["+ beanDefinition +"]");
- }
- }
- elseif(!beanDefinition.equals(existingDefinition)){
- if(logger.isDebugEnabled()){
- logger.debug("Overriding bean definition for bean '"+ beanName +
- "' with a different definition: replacing ["+ existingDefinition +
- "] with ["+ beanDefinition +"]");
- }
- }
- else{
- if(logger.isTraceEnabled()){
- logger.trace("Overriding bean definition for bean '"+ beanName +
- "' with an equivalent definition: replacing ["+ existingDefinition +
- "] with ["+ beanDefinition +"]");
- }
- }
- this.beanDefinitionMap.put(beanName, beanDefinition);
- }
- else{
- if(hasBeanCreationStarted()){
- //注册的过程中需要线程同步,以保证数据的一致性
- synchronized(this.beanDefinitionMap){
- this.beanDefinitionMap.put(beanName, beanDefinition);
- List<String> updatedDefinitions =newArrayList<>(this.beanDefinitionNames.size()+1);
- updatedDefinitions.addAll(this.beanDefinitionNames);
- updatedDefinitions.add(beanName);
- this.beanDefinitionNames = updatedDefinitions;
- removeManualSingletonName(beanName);
- }
- }
- else{
- this.beanDefinitionMap.put(beanName, beanDefinition);
- this.beanDefinitionNames.add(beanName);
- removeManualSingletonName(beanName);
- }
- this.frozenBeanDefinitionNames =null;
- }
-
- //检查是否已经注册过同名的BeanDefinition
- if(existingDefinition !=null||containsSingleton(beanName)){
- //重置所有已经注册过的BeanDefinition的缓存
- resetBeanDefinition(beanName);
- }
- }
至此,Bean配置信息中配置的Bean被解析过后,已经注册到IOC容器中,被容器管理起来,真正完成了IOC容器初始化所做的全部工作。现在IOC容器中已经建立了整个Bean的配置信息,这些BeanDefinition 信息已经可以使用,并且可以被检索,IOC容器的作用就是对这些注册的Bean定义信息进行处理和维护。这些的注册的Bean定义信息是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 通知别人。
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。