Spring 源码分析(四)--自定义标签的使用

    在之前的代码分析中,Spring标签的解析分为 默认标签和自定义标签两种,前一篇文章分析了Spring中对默认标签的解析过程。

    本文将分析Spring中自定义标签的使用过程:

一:回顾

public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {

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

}

  在DefaultBeanDefinitionDocumentReader 类中,分别对默认标签和自定义标签做了不同的解析处理。

二:自定义标签使用

    很多情况下,我们需要为系统提供可配置化支持,简单的做法可以直接基于Spring的标准bean来配置,但配置较为复杂或者需要更多丰富控制的时候,会显得非常笨拙。一般的做法会用原生态的方式取解析定义好的XML文件,然后转化为配置对象。这种方式当然可以解决所有问题,但实现起来比较繁琐,特别是在配置非常复杂的时候,解析工作是一个不得不考虑的负担。Spring提供了可扩展Schema的支持,这是一个不错的折中方案,扩展Spring自定义标签配置大致需要以下几个步骤(前提是要把Spring的Core包加入项目中)。

  • 创建一个需要扩展的组件
  • 定义一个XSD文件描述组件内容
  • 创建一个文件,实现BeanDefinitionParser接口,用来解析XSD文件中的定义和组件定义
  • 创建一个Handler文件,扩展自NamespaceHandlerSupport,目的是将组件注册到Spring容器。
  • 编写Spring.handlers和Spring.schemas文件。

(1)创建一个需要扩展的组件

(2)定义一个XSD文件描述组件内容

(3)创建一个文件,实现BeanDefinitionParser接口,用来解析XSD文件中的定义和组件定义

(4)创建一个Handler文件,扩展自NamespaceHandlerSupport,目的是将组件注册到Spring容器。

(5)编写Spring.handlers和Spring.schemas文件,默认位置是在工程的/META-INF/文件夹下,当然,你可以通过Spring的扩展或者修改源码的方式改变路径。

(6)创建测试配置文件,在配置文件中引入对应的命名空间以及XSD后,便可以直接使用自定义标签了。

(7)测试

原文地址:https://www.cnblogs.com/fdzfd/p/8440629.html