SpringIoC初始化BeanDefinition解析——从Resource到BeanDefinition
2015-09-20 14:15
281 查看
SpringIoC初始化BeanDefinition解析——从Resource到BeanDefinition
上一篇文章解释了spring对Resource的定位过程,今天继续整理一下得到Resource后,spring如果将它转换成内部数据结构BeanDefinition的。从Resource到BeanDefinition大致分为两个过程,首先从Resource中读取xml文件,然后逐个解析xml文件中的标签。xml中的标签又分为两种,其一是默认命名空间下的标签,另外是其他命名空间下标签。本文先总结一下默认命名空间下的标签是怎么转换成BeanDefinition的。上文中提到,XmlBeanDefinitionReader负责BeanDefinition的整个解析过程,接下来直接从拿到Resource后,正式进行解析之前开始。
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException { return loadBeanDefinitions(new EncodedResource(resource)); }
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { Assert.notNull(encodedResource, "EncodedResource must not be null"); if (logger.isInfoEnabled()) { logger.info("Loading XML bean definitions from " + encodedResource.getResource()); } Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get(); if (currentResources == null) { currentResources = new HashSet<EncodedResource>(4); this.resourcesCurrentlyBeingLoaded.set(currentResources); } if (!currentResources.add(encodedResource)) { throw new BeanDefinitionStoreException( "Detected cyclic loading of " + encodedResource + " - check your import definitions!"); } try { InputStream inputStream = encodedResource.getResource().getInputStream(); try { InputSource inputSource = new InputSource(inputStream); if (encodedResource.getEncoding() != null) { inputSource.setEncoding(encodedResource.getEncoding()); } return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); } finally { inputStream.close(); } } catch (IOException ex) { throw new BeanDefinitionStoreException( "IOException parsing XML document from " + encodedResource.getResource(), ex); } finally { currentResources.remove(encodedResource); if (currentResources.isEmpty()) { this.resourcesCurrentlyBeingLoaded.remove(); } } }
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException { try { int validationMode = getValidationModeForResource(resource); Document doc = this.documentLoader.loadDocument( inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware()); return registerBeanDefinitions(doc, resource); } catch (BeanDefinitionStoreException ex) { throw ex; } catch blocks...... }
上面一连串的三个方法实现了从Resource到Document的转变,现在spring才拿到了真正的“配置文件”。第一个方法是一个入口,它封装起了EncodedResource 对象给第二个方法调用;第二个方法中做了重复加载的验证,如果发现已经对当前的资源加载过了,则抛出异常。然后把Resource中的InputStream拿出来封装成了InputSource和Resource一起传给了第三个方法。这里的EncodedResource
其实并没有什么卵用,因为当调用它的equals方法的时候,比较的也是内部的Resource是否相等,而属于它自己的encoding必然是相等的;第三个方法才是xml文档真正读入的地方,它利用documentLoader来获取这个Document对象,真正的实现封装在DefaultDocumentLoader中。DefaultDocumentLoader利用jdk中的DocumentBuilder读取Document对象,感兴趣的读者可以看一下它的具体实现。
得到Document对象后,对于spring来说,下面的任务就是把它翻译成自己的语言BeanDefinition。
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException { BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); documentReader.setEnvironment(this.getEnvironment()); int countBefore = getRegistry().getBeanDefinitionCount(); documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); return getRegistry().getBeanDefinitionCount() - countBefore; }
我们着重看一下上面的方法,它的目的是从Document中解析出所有的BeanDefinition,并且把它们注册到Registry中,返回新发现的BeanDefinition的数量。这里用到了一个重要的类BeanDefinitionDocumentReader,整个解析和注册的过程都交给了它,它的具体实现类是DefaultBeanDefinitionDocumentReader,创建过程很简单,如下面代码。
private Class<?> documentReaderClass = DefaultBeanDefinitionDocumentReader.class;
protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() { return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass)); }
创建了BeanDefinitionDocumentReader后,XmlBeanDefinitionReader又创建了XmlReaderContext。这个XmlReaderContext是xml文档解析期间的上下文,贯穿整个解析过程。
protected XmlReaderContext createReaderContext(Resource resource) { if (this.namespaceHandlerResolver == null) { this.namespaceHandlerResolver = createDefaultNamespaceHandlerResolver(); } return new XmlReaderContext(resource, this.problemReporter, this.eventListener, this.sourceExtractor, this, this.namespaceHandlerResolver); }
做好了准备工作,BeanDefinitionDocumentReader就可以开始逐行的解析Document文档了。
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) { this.readerContext = readerContext; logger.debug("Loading bean definitions"); Element root = doc.getDocumentElement(); doRegisterBeanDefinitions(root); }
protected void doRegisterBeanDefinitions(Element root) { String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE); if (StringUtils.hasText(profileSpec)) { Assert.state(this.environment != null, "environment property must not be null"); String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS); if (!this.environment.acceptsProfiles(specifiedProfiles)) { return; } } BeanDefinitionParserDelegate parent = this.delegate; this.delegate = createHelper(readerContext, root, parent); preProcessXml(root); parseBeanDefinitions(root, this.delegate); postProcessXml(root); this.delegate = parent; }终于,终于我们有了xml文档的内容root Element。这里又出现了一个非常非常重要的类BeanDefinitionParserDelegate,出现在前面的调用链上的所有类都是对BeanDefinition解析过程的封装,而这个类则是具体的干活的类,是它对每个文档逐行的分析,完成BeanDefinition的解析。赶快看一下XmlBeanDefinitionReader是怎么指挥BeanDefinitionParserDelegate完成它们的工作的。
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { if (delegate.isDefaultNamespace(root)) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; if (delegate.isDefaultNamespace(ele)) { parseDefaultElement(ele, delegate); } else { delegate.parseCustomElement(ele); } } } } else { delegate.parseCustomElement(root); } }如文章开头所讲,xml文档中的标签分两类,默认命名空间的标签和非默认命名空间的标签。对应处理他们的方法分别是parseDefaultElement和parseCustomElement。本文先了解默认命名空间下BeanDefinition的解析过程,非默认命名空间标签的解析过程后续整理一下。
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) { if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) { importBeanDefinitionResource(ele); } else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) { processAliasRegistration(ele); } else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) { processBeanDefinition(ele, delegate); } else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { // recurse doRegisterBeanDefinitions(ele); } }
默认命名空间下可能有四种标签,import,alias,bean和beans。import的意思是引用另一处配置文件的内容,处理import标签有是一个从Resource定位到BeanDefinition解析注册的完整过程;alias标签的作用是给bean起别名,所以不用再重复的解析BeanDefinition,直接把别名进行注册即可;beans应该出现是文档的root Element,这里如果发现beans标签则调用刚才的doRegisterBeanDefinitions方法;bean标签是一个正常的定义spring
bean的标签,里面包含了类型、属性以及构造函数等信息,下面来看一下利用这些信息构造BeanDefinition的过程。
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); try { // Register the final decorated instance. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); } catch (BeanDefinitionStoreException ex) { getReaderContext().error("Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, ex); } // Send registration event. getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); } }
可以看到,delegate完成了BeanDefinition的解析过程,并把它放到BeanDefinitionHolder中。下面的decorateBeanDefinitionIfRequired对于默认命名空间下的标签没有影响,注册过程本文先不涉及。来看delegate中的parseBeanDefinitionElement方法。
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) { return parseBeanDefinitionElement(ele, null); }
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) { String id = ele.getAttribute(ID_ATTRIBUTE); String nameAttr = ele.getAttribute(NAME_ATTRIBUTE); List<String> aliases = new ArrayList<String>(); if (StringUtils.hasLength(nameAttr)) { String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS); aliases.addAll(Arrays.asList(nameArr)); } String beanName = id; if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) { beanName = aliases.remove(0); if (logger.isDebugEnabled()) { logger.debug("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases + " as aliases"); } } if (containingBean == null) { checkNameUniqueness(beanName, aliases, ele); } AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean); if (beanDefinition != null) { if (!StringUtils.hasText(beanName)) { try { if (containingBean != null) { beanName = BeanDefinitionReaderUtils.generateBeanName( beanDefinition, this.readerContext.getRegistry(), true); } else { beanName = this.readerContext.generateBeanName(beanDefinition); // Register an alias for the plain bean class name, if still possible, // if the generator returned the class name plus a suffix. // This is expected for Spring 1.2/2.0 backwards compatibility. String beanClassName = beanDefinition.getBeanClassName(); if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } if (logger.isDebugEnabled()) { logger.debug("Neither XML 'id' nor 'name' specified - " + "using generated bean name [" + beanName + "]"); } } catch (Exception ex) { error(ex.getMessage(), ele); return null; } } String[] aliasesArray = StringUtils.toStringArray(aliases); return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray); } return null; }
public AbstractBeanDefinition parseBeanDefinitionElement( Element ele, String beanName, BeanDefinition containingBean) { this.parseState.push(new BeanEntry(beanName)); String className = null; if (ele.hasAttribute(CLASS_ATTRIBUTE)) { className = ele.getAttribute(CLASS_ATTRIBUTE).trim(); } try { String parent = null; if (ele.hasAttribute(PARENT_ATTRIBUTE)) { parent = ele.getAttribute(PARENT_ATTRIBUTE); } AbstractBeanDefinition bd = createBeanDefinition(className, parent); parseBeanDefinitionAttributes(ele, beanName, containingBean, bd); bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT)); parseMetaElements(ele, bd); parseLookupOverrideSubElements(ele, bd.getMethodOverrides()); parseReplacedMethodSubElements(ele, bd.getMethodOverrides()); parseConstructorArgElements(ele, bd); parsePropertyElements(ele, bd); parseQualifierElements(ele, bd); 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(); } return null; }
上面的方法,看名字就可以知道其实现的逻辑。首先需要单独的处理bean的id、name和alias,保证它们的唯一性。然后再去寻找其它标签,把标签中的内容取出来,放到BeanDefinition中。涉及到的代码非常多,但思想非常简单清晰,有兴趣的读者自己参考源码。
其实,BeanDefinition的解析过程就是把xml文件翻译成BeanDefinition的过程。BeanDefinition是spring内部通用的语言。xml文档是我们开发者的语言,是spring为我们提供的沟通窗口,通过这个窗口我们可以把序列化好的信息传递给spring。而spring对xml文档进行翻译也就是把我们序列化的内容反序列出来,只是序列化前后的系统和格式不同。
相关文章推荐
- JDK中工具类的使用
- SpringMVC开发过程中的中文乱码问题
- java 静态导入
- Ubuntu下安装 Eclipse
- ubuntu安装配置jdk1.7
- java基础之接口(抽象类与接口的区别)
- java基础之接口(抽象类与接口的区别)
- java.sql.SQLException错误
- windows安装eclipse+MinGW编译c程序
- 禁止浏览器缓存- make sure web page is not cached
- Struts、hibernate、Spring 官网下载步骤
- JAVA
- JAVA
- JavaEE系列之(二)commons-fileupload实现文件上传、下载
- Spring.Web.Mvc 注入(控制器属性注入)
- Java多线程中的竞争条件、锁以及同步的概念
- Spring如何扫描class和配置文件
- 大龄屌丝自学笔记--Java零基础到菜鸟--020
- 解决 - java.lang.OutOfMemoryError: unable to create new native thread
- MySQL:连接MyEclipse