乐趣区

Spring源码3自定义标签的解析

背景

上一篇我们介绍了默认标签的解析,本篇我们介绍默自定义标签的解析

1. 修改原有工程

1.1 首先创建一个 POJO,用来接收配置文件参数

User.class

public class User {
    private String id;
    private String userName;
    private String email;

    get/set 方法省略
}

1.2 定义一个 XSD 文件描述组件的内容

user.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns="http://www.wjs.com/schema/user" targetNamespace="http://www.wjs.com/schema/user"
            elementFormDefault="qualified">
    <xsd:element name="user">
        <xsd:complexType>
            <xsd:attribute name="id" type="xsd:string" />
            <xsd:attribute name="userName" type="xsd:string" />
            <xsd:attribute name="email" type="xsd:string" />
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

1.3 创建 java 类实现 AbstractSingleBeanDefinitionParser 接口,用来解析 XSD 文件中的定义和组件

UserBeanDefinitionParser.class

public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
    @Override
    protected Class getBeanClass(Element element){return User.class;}

    @Override
    protected void doParse(Element element, BeanDefinitionBuilder bean){String userName = element.getAttribute("userName");
        String email =  element.getAttribute("email");

        if(StringUtils.hasText(userName)){bean.addPropertyValue("userName",userName);
        }
        if(StringUtils.hasText(email)){bean.addPropertyValue("email",email);
        }
    }
}

1.4 创建 Handler 文件,将组件注册到 Spring 容器

MyNamespaceHandler.class

public class MyNamespaceHandler extends NamespaceHandlerSupport {public void init() {registerBeanDefinitionParser("user",new UserBeanDefinitionParser());
    }
}

1.5 创建配置文件

1.5.1handler 配置文件

spring.handlers

http\://www.wjs.com/schema/user=com.zero.test.MyNamespaceHandler
1.5.2XSD 配置文件

spring.schemas

http\://www.wjs.com/schema/user.xsd=META-INF/user.xsd

1.6 修改配置文件,在配置文件中引入命名空间和 XSD

beans.xml

命名空间

xmlns:myName="http://www.wjs.com/schema/user"

XSD

http://www.wjs.com/schema/user http://www.wjs.com/schema/user.xsd"
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:myName="http://www.wjs.com/schema/user"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.wjs.com/schema/user http://www.wjs.com/schema/user.xsd">

    <myName:user id="testBean" userName="name" email="A"/>

<!--            <bean id = "testBean" class="com.zero.pojo.User">-->
<!--                <property name="userName" value="zhang"></property>-->
<!--                <property name="email" value = "18"></property>-->

<!--            </bean>-->
</beans>


2. 对自定义类型标签进行处理

delegate.parseCustomElement(ele);

还是在解析标签的地方

parseBeanDefinitions(root, this.delegate);

    /**
     * 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)) {parseDefaultElement(ele, delegate);
                    }
                    else {
                           // 自定义标签
                        delegate.parseCustomElement(ele);
                    }
                    
                    
                }
            }
        }
        else {// 自定义标签
            delegate.parseCustomElement(root);
        }
    }

根据对应的 bean 获取对应的命名空间,根据命名空间解析对应的处理器,然后根据对应的处理器进行解析

    
    @Nullable
    public BeanDefinition parseCustomElement(Element ele) {return parseCustomElement(ele, null);
    }

    //containingBd 为父类 bean,对顶层元素解析设置为 null        
    @Nullable
    public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
        // 获取对应命名空间
        String namespaceUri = this.getNamespaceURI(ele);
        if (namespaceUri == null) {return null;} else {
             // 根据命名空间找对应 NamespaceHandler
            NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
            if (handler == null) {this.error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
                return null;
            } else {
                // 调用自定义 NameSpaceHandler 进行解析
                return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
            }
        }
    }

2.1 获取命名空间,命名空间已经解析到 Node 中

String namespaceUri = this.getNamespaceURI(ele);

    @Nullable
    public String getNamespaceURI(Node node) {return node.getNamespaceURI();
    }

2.2 获取自定义的标签处理器

NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);

如果要使用自定义标签,其中一项就是在 spring.handlers 文件中找到配置的命名空间和命名空间处理器之间的映射关系,找到后才能根据映射关系找到匹配的处理器,在代码中实现就是通过反射执行 init 方法来进行 BeanDefinitionParser 的注册,注册后命名空间处理器根据标签的不同调用不同的解析器进行解析

    /**
     * Locate the {@link NamespaceHandler} for the supplied namespace URI
     * from the configured mappings.
     * @param namespaceUri the relevant namespace URI
     * @return the located {@link NamespaceHandler}, or {@code null} if none found
     */
    @Override
    @Nullable
    public NamespaceHandler resolve(String namespaceUri) {
         // 获取已经配置的 handler 映射
        Map<String, Object> handlerMappings = getHandlerMappings();
         // 根据命名空间找到对应信息
        Object handlerOrClassName = handlerMappings.get(namespaceUri);
        if (handlerOrClassName == null) {return null;}
         // 已经做过解析的情况,直接从缓存中取
        else if (handlerOrClassName instanceof NamespaceHandler) {return (NamespaceHandler) handlerOrClassName;
        }
        else {
             // 没有做过解析,返回类路径
            String className = (String) handlerOrClassName;
            try {
                 // 使用反射将类路径转化为类
                Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
                if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) {throw new FatalBeanException("Class [" + className + "] for namespace [" + namespaceUri +
                            "] does not implement the [" + NamespaceHandler.class.getName() + "] interface");
                }
                 // 初始化类
                NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass);
                 // 调用自定义的 NamespaceHandler 的初始化方法
                namespaceHandler.init();
                 // 记录在缓存中
                handlerMappings.put(namespaceUri, namespaceHandler);
                return namespaceHandler;    
            }
            catch (ClassNotFoundException ex) {
                throw new FatalBeanException("Could not find NamespaceHandler class [" + className +
                        "] for namespace [" + namespaceUri + "]", ex);
            }
            catch (LinkageError err) {
                throw new FatalBeanException("Unresolvable class definition for NamespaceHandler class [" +
                        className + "] for namespace [" + namespaceUri + "]", err);
            }
        }
    }
2.2.1 获取已经配置的 handler 映射

Map<String, Object> handlerMappings = getHandlerMappings();

    /**
     * Load the specified NamespaceHandler mappings lazily.
     */
    private Map<String, Object> getHandlerMappings() {
        Map<String, Object> handlerMappings = this.handlerMappings;
         // 如果没有被缓存,则开始缓存
        if (handlerMappings == null) {
             // 锁定
            synchronized (this) {
                handlerMappings = this.handlerMappings;
                if (handlerMappings == null) {
                    try {
                          //this.handlerMappingsLocation 在构造函数中已经初始化为 META-INF/spring.handlers    
                          // 借助工具类 PropertiesLoaderUtils 读取 handlerMappingsLocation 的配置文件
                        Properties mappings =
                                PropertiesLoaderUtils.loadAllProperties(this.handlerMappingsLocation, this.classLoader);
                        if (logger.isDebugEnabled()) {logger.debug("Loaded NamespaceHandler mappings:" + mappings);
                        }
                        Map<String, Object> mappingsToUse = new ConcurrentHashMap<>(mappings.size());
                          // 将 Properties 格式文件合并到 Map 格式的 handlerMappings 中
                        CollectionUtils.mergePropertiesIntoMap(mappings, mappingsToUse);
                        handlerMappings = mappingsToUse;
                        this.handlerMappings = handlerMappings;
                    }
                    catch (IOException ex) {
                        throw new IllegalStateException("Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]", ex);
                    }
                }
            }
        }
        return handlerMappings;
    }

2.3 标签解析

return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));

寻找标签解析器并进行解析,此时 handler 已经实例化为 MyNamespaceHandler,而且 MyNamespaceHandler 也完成了初始化 (在 resolve 中使用反射初始化并执行了 init 方法)

    /**
     * Parses the supplied {@link Element} by delegating to the {@link BeanDefinitionParser} that is
     * registered for that {@link Element}.
     */
    @Override
    @Nullable
    public BeanDefinition parse(Element element, ParserContext parserContext) {
         // 寻找解析器,并进行解析操作
        BeanDefinitionParser parser = findParserForElement(element, parserContext);
        return (parser != null ? parser.parse(element, parserContext) : null);
    }
2.3.1 寻找解析器,并进行解析操作

BeanDefinitionParser parser = findParserForElement(element, parserContext);

    /**
     * Locates the {@link BeanDefinitionParser} from the register implementations using
     * the local name of the supplied {@link Element}.
     */
    @Nullable
    private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
         // 获取元素名称,也就是 <myname:user 中的 user,若在示例中,此 localName 为 user
        String localName = parserContext.getDelegate().getLocalName(element);
        // 根据 user 找到对应的解析器,也就是 handler 中的    registerBeanDefinitionParser("user",new UserBeanDefinitionParser());
        // 注册的解析器
        BeanDefinitionParser parser = this.parsers.get(localName);
        if (parser == null) {parserContext.getReaderContext().fatal("Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
        }
        return parser;
    }
2.3.2 解析并将 AbstractBeanDefinition 转换为 BeanDefinitionHolder 并注册
    @Override
    @Nullable
    public final BeanDefinition parse(Element element, ParserContext parserContext) {AbstractBeanDefinition definition = parseInternal(element, parserContext);
        if (definition != null && !parserContext.isNested()) {
            try {String id = resolveId(element, definition, parserContext);
                if (!StringUtils.hasText(id)) {parserContext.getReaderContext().error("Id is required for element'" + parserContext.getDelegate().getLocalName(element)
                                    + "'when used as a top-level tag", element);
                }
                String[] aliases = null;
                if (shouldParseNameAsAliases()) {String name = element.getAttribute(NAME_ATTRIBUTE);
                    if (StringUtils.hasLength(name)) {aliases = StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
                    }
                }
                 // 将 AbstractBeanDefinition 转换为 BeanDefinitionHolder 并注册
                BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id, aliases);
                registerBeanDefinition(holder, parserContext.getRegistry());
                if (shouldFireEvents()) {
                      // 需要通知监听器进行处理
                    BeanComponentDefinition componentDefinition = new BeanComponentDefinition(holder);
                    postProcessComponentDefinition(componentDefinition);
                    parserContext.registerComponent(componentDefinition);
                }
            }
            catch (BeanDefinitionStoreException ex) {String msg = ex.getMessage();
                parserContext.getReaderContext().error((msg != null ? msg : ex.toString()), element);
                return null;
            }
        }
        return definition;
    }
2.3.3 自定义配置文件的解析

AbstractBeanDefinition definition = parseInternal(element, parserContext);\

在 parserInternal 中并不是直接调用自定义的 doParse 函数,而是进行一系列的数据准备操作,包括对 beanClass、scope、lazyInit 等属性的准备,然后执行子类中重写的 doParse 方法

UserBeanDefinitionParser 重写了 org.springframework.beans.factory.xmlAbstractSingleBeanDefinitionParser 中的 doParse 方法

package org.springframework.beans.factory.xml;

public abstract class AbstractSingleBeanDefinitionParser extends AbstractBeanDefinitionParser    

    /**
     * Creates a {@link BeanDefinitionBuilder} instance for the
     * {@link #getBeanClass bean Class} and passes it to the
     * {@link #doParse} strategy method.
     * @param element the element that is to be parsed into a single BeanDefinition
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the BeanDefinition resulting from the parsing of the supplied {@link Element}
     * @throws IllegalStateException if the bean {@link Class} returned from
     * {@link #getBeanClass(org.w3c.dom.Element)} is {@code null}
     * @see #doParse
     */
    @Override
    protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
        String parentName = getParentName(element);
        if (parentName != null) {builder.getRawBeanDefinition().setParentName(parentName);
        }
         // 获取自定义标签中的 class,此时会调用自定义解析器如 UserBeanDefinitionParser 中的 getBeanClass 方法
        Class<?> beanClass = getBeanClass(element);
        if (beanClass != null) {
             // 设置 beanClass 为 User.class
            builder.getRawBeanDefinition().setBeanClass(beanClass);
        }
        else {
             // 若子类没有重写 getBeanClass 方法则尝试检查子类是否重写 getBeanClassName 方法
            String beanClassName = getBeanClassName(element);
            if (beanClassName != null) {builder.getRawBeanDefinition().setBeanClassName(beanClassName);
            }
        }
        builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
        BeanDefinition containingBd = parserContext.getContainingBeanDefinition();
        if (containingBd != null) {
             // 若存在父类,则使用父类的 scope 属性
            // Inner bean definition must receive same scope as containing bean.
            builder.setScope(containingBd.getScope());
        }
        if (parserContext.isDefaultLazyInit()) {
             // 配置延迟加载
            // Default-lazy-init applies to custom bean definitions as well.
            builder.setLazyInit(true);
        }
         // 调用子类重写的 doParse 方法进行解析,也就是 UserBeanDefinitionParser 中的 doParse
        doParse(element, parserContext, builder);
        return builder.getBeanDefinition();}


    /**
     * Parse the supplied {@link Element} and populate the supplied
     * {@link BeanDefinitionBuilder} as required.
     * <p>The default implementation delegates to the {@code doParse}
     * version without ParserContext argument.
     * @param element the XML element being parsed
     * @param parserContext the object encapsulating the current state of the parsing process
     * @param builder used to define the {@code BeanDefinition}
     * @see #doParse(Element, BeanDefinitionBuilder)
     */
    protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {doParse(element, builder);
    }

自定义标签解析结束

退出移动版