转载

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);
    }

自定义标签解析结束

原文  https://segmentfault.com/a/1190000023064961
正文到此结束
Loading...