从xml到document
从document到beanDefinition
从beanDefiniton到instance
涉及到的部分主要类或接口:
org.springframework.beans.factory.xml.BeanDefinitionDocumentReader
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader
org.springframework.beans.factory.xml.BeanDefinitionParserDelegate
org.springframework.beans.factory.support.BeanDefinitionReaderUtils
org.springframework.beans.factory.config.BeanDefinition
org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver
从document到beanDefinition
从最直接的xml配置开始
对于像事务tx:annotation等标签在spring-tx.jar/META-INF/spring.handlers下有配置具体的处理类。bean是不是也有一样的配置呢,其实不然,我们找到解析注册标签的入口。
省略从web.xml加载到doc的过程,从解析Element root = doc.getDocumentElement()开始
解析根节点root的任务由DefaultBeanDefinitionDocumentReader开始
DefaultBeanDefinitionDocumentReader源码:
http://www.grepcode.com/file/repository.springsource.com/org.springframework/org.springframework.beans/3.2.2/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java/
DefaultBeanDefinitionDocumentReader.parseBeanDefinitions
/** * Parse the elements at the root level in the document: * "import", "alias", "bean". * @param root the DOM root element of the document */ 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)) { //1.处理默认标签 parseDefaultElement(ele, delegate); } else { delegate.parseCustomElement(ele); } } } } else { delegate.parseCustomElement(root); } }
对于默认的标签,如"import", "alias", "bean" 在parseDefaultElement处开始解析。非默认的标签需定义schema/handlers进行处理。
查看默认标签的处理方法:
DefaultBeanDefinitionDocumentReader#parseDefaultElement
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) { //1.1 处理import标签 if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) { importBeanDefinitionResource(ele); } //1.2 处理alias标签 else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) { processAliasRegistration(ele); } //1.3 处理bean标签 else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) { processBeanDefinition(ele, delegate); } else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { // recurse doRegisterBeanDefinitions(ele); } }
继续bean标签的处理BEAN_ELEMENT:
DefaultBeanDefinitionDocumentReader#processBeanDefinition
/** * Process the given bean element, parsing the bean definition * and registering it with the registry. */ protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { //1.3.1 生成beanDefinitionHolder BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { //1.3.2 解析bean标签的自定义元素 //扩展BeanDefinition-自定义标签 bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); try { //1.3.3 注册beanDefinitionMap // 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)); } }
从以上代码可以看到,DefaultBeanDefinitionDocumentReader将解析生成beanDefinition的任务委托给了BeanDefinitionParserDelegate进行处理。
beanDefinitionDocumentReader
-------------------------------------------------------承上启下的分割线----------------------------------------------
beanDefinitionParserDelegate
BeanDefinitionParserDelegate源码:
http://grepcode.com/file/repository.springsource.com/org.springframework/org.springframework.beans/3.2.2/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java#BeanDefinitionParserDelegate
由上可知,处理bean标签分3个部分:
一是解析bean标签生成BeanDefinitionHolder- 处理spring默认元素或属性
BeanDefinitionParserDelegate#parseBeanDefinitionElement
/** * Parses the supplied {@code <bean>} element. May return {@code null} * if there were errors during parse. Errors are reported to the * {@link org.springframework.beans.factory.parsing.ProblemReporter}. */ public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) { String id = ele.getAttribute(ID_ATTRIBUTE); String nameAttr = ele.getAttribute(NAME_ATTRIBUTE); Listaliases = new ArrayList (); 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; }
可以看到,先生成beanDefinition再包装成beanDefinitionHolder
(1)生成beanDefinition的过程
BeanDefinitionParserDelegate#createBeanDefinition
protected AbstractBeanDefinition createBeanDefinition(String className, String parentName) throws ClassNotFoundException { return BeanDefinitionReaderUtils.createBeanDefinition( parentName, className, this.readerContext.getBeanClassLoader()); }
创建GenericBeanDefinition
BeanDefinitionReaderUtils#createBeanDefinition
public static AbstractBeanDefinition createBeanDefinition( String parentName, String className, ClassLoader classLoader) throws ClassNotFoundException { GenericBeanDefinition bd = new GenericBeanDefinition(); bd.setParentName(parentName); if (className != null) { if (classLoader != null) { bd.setBeanClass(ClassUtils.forName(className, classLoader)); } else { bd.setBeanClassName(className); } } return bd; }
这里可以发挥你的想象力。就像平时定义了一个model,然后设置各种属性的过程。 这里处理的属性或子标签都是spring默认定义的属性或标签,自定义的标签会在第二步进行处理
bd.setBeanClass涉及到从benDefintion到instance的一个处理过程:resolveBeanClass
如果这里设置了beanClass,resolveBeanClass可以直接返回。
那这里会不会设置beanClass呢?
关键点是this.readerContext.getBeanClassLoader(),其里面继续调用XmlBeanDefinitionReader.getBeanClassLoader();
查看
这里定义的beanDefinition的实际类是GenericBeanDefinition,在从beanDefinition到instance的过程中,会转为RootBeanDefinition
平常我们只会设置几个熟悉的属性,其实beanDefinition中有很多属性,
例如:lookup-method replace-method等
spring是如何解析这些特殊属性或标签的来生成实例的呢?
其他属性可查看BeanDefinitionParserDelegate的源码,其用静态变量基本定义了所有属性
(2)此时生成的beanDefinitionHolder对象也很简单,只是存储了beanDefinition及其名称等
二是装饰第一步生成的BeanDefinitionHolder对象- 处理自定义标签或属性- 可以看做spring的一种扩展-对spring的默认标签进行扩展
public BeanDefinitionHolder decorateBeanDefinitionIfRequired( Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd) { BeanDefinitionHolder finalDefinition = definitionHolder; // Decorate based on custom attributes first. NamedNodeMap attributes = ele.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node node = attributes.item(i); finalDefinition = decorateIfRequired(node, finalDefinition, containingBd); } // Decorate based on custom nested elements. NodeList children = ele.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { finalDefinition = decorateIfRequired(node, finalDefinition, containingBd); } } return finalDefinition; }
// Decorate based on custom attributes first.
NamedNodeMap attributes = ele.getAttributes();
// Decorate based on custom nested elements.
NodeList children = ele.getChildNodes();
这里继续循环bean标签的属性或子标签,难道是继续对第一步的属性进行深入处理?其实不然,继续跟到decorateIfRequired方法中看看
private BeanDefinitionHolder decorateIfRequired( Node node, BeanDefinitionHolder originalDef, BeanDefinition containingBd) { String namespaceUri = getNamespaceURI(node); if (!isDefaultNamespace(namespaceUri)) { NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri); if (handler != null) { return handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd)); } else if (namespaceUri != null && namespaceUri.startsWith("http://www.springframework.org/")) { error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node); } else { // A custom namespace, not to be handled by Spring - maybe "xml:...". if (logger.isDebugEnabled()) { logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]"); } } } return originalDef; }
这段代码中,有个很重要的分子判断!isDefaultNamespace(namespaceUri),即是否是自定义标签,如果不是则继续获取相应命名空间处理类进行解析
可见装饰主要是对自定义子标签或属性的解析过程- 对spring bean标签的扩展
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
this.readerContext.getNamespaceHandlerResolver()获取的是DefaultNamespaceHandlerResolver,其主要职责是管理命名空间处理器的。其数据来源主要是META-INF/spring.handlers下的内容,加载这些文件用到了懒加载机制(Load the specified NamespaceHandler mappings lazily)
resolve方法中,首先加载META-INF/spring.handler文件:
Properties mappings = PropertiesLoaderUtils.loadAllProperties(this.handlerMappingsLocation, this.classLoader);
并将其Properties类中的文件,转换为hashMap缓存起来:
CollectionUtils.mergePropertiesIntoMap(mappings, handlerMappings);
再就是根据命名空间,读取相应命名空间处理器,并初始化返回:
NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass);
将namespaceHandler放入handlerMappings中(之前将Properties转换为hashMap,value值只是string类型的)
handlerMappings.put(namespaceUri, namespaceHandler);
可跟踪源代码,借鉴spring是如何读取配置文件的
DefaultNamespaceHandlerResolver源码:
http://grepcode.com/file/repository.springsource.com/org.springframework/org.springframework.beans/3.2.2/org/springframework/beans/factory/xml/DefaultNamespaceHandlerResolver.java/
三是注册到beanDefinition容器
// Register the final decorated instance. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
/** * Register the given bean definition with the given bean factory. * @param definitionHolder the bean definition including name and aliases * @param registry the bean factory to register with * @throws BeanDefinitionStoreException if registration failed */ public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { // Register bean definition under primary name. String beanName = definitionHolder.getBeanName(); registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // Register aliases for bean name, if any. String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String aliase : aliases) { registry.registerAlias(beanName, aliase); } } }
这里registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());实际上就是放到 DefaultListableBeanFactory.beanDefinitionMap中
至此,从document到beanDefinition分析结束