溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring自定義Xml標(biāo)簽的使用方法

發(fā)布時間:2021-06-21 13:57:19 來源:億速云 閱讀:211 作者:chen 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Spring自定義Xml標(biāo)簽的使用方法”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Spring自定義Xml標(biāo)簽的使用方法”吧!

目錄
  • 前言

  • 正文

  • 自定義NameSpaceHandler

  • 自定義schema

  • Parser

  • Decorator

  • 總結(jié)

前言

在早期基于Xml配置的Spring Mvc項目中,我們往往會使用<context:component-scan basePackage="">這種自定義標(biāo)簽來掃描我們在basePackae配置里的包名下的類,并且會判斷這個類是否要注入到Spring容器中(比如這個類上標(biāo)記了@Component注解就代表需要被Spring注入),如果需要那么它會幫助我們把這些類一一注入。

正文

在分析這個自定義標(biāo)簽的解析機(jī)制前,我先提前劇透這個自定義標(biāo)簽是通過哪個強(qiáng)大的類來解析的吧,就是隸屬于spring-context包下的ComponentScanBeanDefinitionParser,這個類在Springboot掃描Bean的過程中也扮演了重要角色。

既然知道了是這個類解析的,那么我們可以通過idea強(qiáng)大的搜索功能來搜它的引用之處了,這邊就截圖如下:

Spring自定義Xml標(biāo)簽的使用方法

可以看到這里面初始化了8個帶Parser后綴的各種Parser,從方法registerBeanDefinitionParser看出Spring是通過這個ContextNamespaceHandler來完成對以<context:自定義命名空間開頭的標(biāo)簽解析器的注冊。我們可以看到Spring內(nèi)部已經(jīng)集成了幾個常用的NamespaceHandler,截圖如下:

Spring自定義Xml標(biāo)簽的使用方法

那么我們自己是否可以自定義一個NamespaceHandler來注冊我們自定義的標(biāo)簽解析器呢?答案是肯定的。

自定義NameSpaceHandler

final class TestNamespaceHandler extends NamespaceHandlerSupport {

   @Override
   public void init() {

      //注冊parser
      registerBeanDefinitionParser("testBean", new TestBeanDefinitionParser());
      registerBeanDefinitionParser("person", new PersonDefinitionParser());

      //注冊element的 decorater
      registerBeanDefinitionDecorator("set", new PropertyModifyingBeanDefinitionDecorator());
      registerBeanDefinitionDecorator("debug", new DebugBeanDefinitionDecorator());

      //注冊 attr的 decorator
      registerBeanDefinitionDecoratorForAttribute("object-name", new ObjectNameBeanDefinitionDecorator());
   }

到這里大家可能會有個疑問,這個NameSpaceHandler是怎么使用的呢?大家如果看了我之前寫的文章,那就會知道有一種方式可以配置我們自定義的NamespaceHandler.

public class CustomXmlApplicationContext  extends AbstractXmlApplicationContext {

   private static final String CLASSNAME = CustomXmlApplicationContext.class.getSimpleName();
   private static final String FQ_PATH = "org/wonder/frame/customBean";
   private static final String NS_PROPS = format("%s/%s.properties", FQ_PATH, CLASSNAME);

   public CustomXmlApplicationContext(String... configLocations) {
      setConfigLocations(configLocations);
         refresh();
   }

   @Override
   protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
      super.initBeanDefinitionReader(reader);

      //1.指定resolver的 handlerMappingsLocation 就是 NamespaceHandler的 配置文件路徑
      NamespaceHandlerResolver resolver = new DefaultNamespaceHandlerResolver(this.getClassLoader(), NS_PROPS);

      //2.設(shè)置resolver
      reader.setNamespaceHandlerResolver(resolver);
      //3.設(shè)置驗證模式
      reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
      //4.設(shè)置entityResolver
      reader.setEntityResolver(new CustomSchemaResolver());
   }

可以看到我們在初始化BeanDefinitionReader的時候我們可以設(shè)置NamespaceHandlerResolver并且配置它的NamespaceHandler文件路徑。那這個NamespaceHandler配置文件應(yīng)該怎么寫呢?

http\://www.john.com/resource=org.wonder.frame.customBean.TestNamespaceHandler

就一行配置,但是這里有兩點(diǎn)要注意:

  • http\://www.john.com/resource要和xsd的targetNamspace一致。

  • http\://www.john.com/resource要和xml配置文件中的自定義namespace一致。

從代碼里看出來我們解析自定義標(biāo)簽的時候其實是還需要自定義schema才能完成的。

自定義schema

private static final String CLASSNAME = CustomXmlApplicationContext.class.getSimpleName();
private static final String FQ_PATH = "org/wonder/frame/customBean";
private static final String TEST_XSD = format("%s/%s.xsd", FQ_PATH, CLASSNAME);
private final class CustomSchemaResolver extends PluggableSchemaResolver {

   public CustomSchemaResolver() {
      super(CustomXmlApplicationContext.this.getClassLoader());
   }

   @Override
   public InputSource resolveEntity(String publicId, String systemId) throws IOException {
      InputSource source = super.resolveEntity(publicId, systemId);
      if (source == null) {
         try{
            //todo 指定了xsd路徑
            Resource resource = new ClassPathResource(TEST_XSD);
            source = new InputSource(resource.getInputStream());
            source.setPublicId(publicId);
            source.setSystemId(systemId);
            return source;
         }
         catch (FileNotFoundException ex){

         }

      }
      return  null;
   }
}

這里我們也通過ClassPathResource設(shè)置了自定義的xsd文件路徑。我們來看看xsd文件長啥樣:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<xsd:schema xmlns="http://www.john.com/resource"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
         targetNamespace="http://www.john.com/resource"
         elementFormDefault="qualified">

   <xsd:element name="person">
      <xsd:complexType>
         <xsd:attribute name="id" type="xsd:string" use="optional" form="unqualified"/>
         <xsd:attribute name="name" type="xsd:string" use="required" form="unqualified"/>
         <xsd:attribute name="age" type="xsd:integer" use="required" form="unqualified"/>
      </xsd:complexType>
   </xsd:element>

   <xsd:element name="testBean">
      <xsd:complexType>
         <xsd:attribute name="id" type="xsd:string" use="required" form="unqualified"/>
         <xsd:attribute name="name" type="xsd:string" use="required" form="unqualified"/>
         <xsd:attribute name="age" type="xsd:integer" use="required" form="unqualified"/>
      </xsd:complexType>
   </xsd:element>

   <xsd:element name="set">
      <xsd:complexType>
         <xsd:attribute name="name" type="xsd:string" use="required" form="unqualified"/>
         <xsd:attribute name="age" type="xsd:integer" use="required" form="unqualified"/>
      </xsd:complexType>
   </xsd:element>

   <xsd:element name="debug"/>
   <xsd:attribute name="object-name" type="xsd:string"/>
</xsd:schema>

Parser

我們先來分析下TestBeanDefinitionParser和PersonDefinitionParser這兩者有啥區(qū)別:

TestBeanDefinitionParser直接實現(xiàn)了BeanDefinitionParser接口,內(nèi)部直接定義一個RootBeanDefinition并且注冊。

private static class TestBeanDefinitionParser implements BeanDefinitionParser {

   @Override
   public BeanDefinition parse(Element element, ParserContext parserContext) {

      RootBeanDefinition definition = new RootBeanDefinition();
      definition.setBeanClass(CustomBean.class);

      MutablePropertyValues mpvs = new MutablePropertyValues();
      mpvs.add("name", element.getAttribute("name"));
      mpvs.add("age", element.getAttribute("age"));

      //1.設(shè)置beanDefinition的 屬性 propertyValues
      definition.setPropertyValues(mpvs);

      //2.獲取到beanDefinition的 registry
      parserContext.getRegistry().registerBeanDefinition(element.getAttribute("id"), definition);
      return null;
   }
}

PersonDefinitionParser繼承自AbstractSingleBeanDefinitionParser抽象類,內(nèi)部使用BeanDefinitionBuilder構(gòu)造器來完成BeanDefinition的創(chuàng)建。

private static final class PersonDefinitionParser extends AbstractSingleBeanDefinitionParser {

   @Override
   protected Class<?> getBeanClass(Element element) {
      return CustomBean.class;
   }

   @Override
   protected void doParse(Element element, BeanDefinitionBuilder builder) {
      builder.addPropertyValue("name", element.getAttribute("name"));
      builder.addPropertyValue("age", element.getAttribute("age"));
   }
}

Decorator

我們看到在NameSpaceHandler中我們除了parser外還可以定義自定義元素的decorator和自定義attribute的decorator,那這兩個decorator是用來干嘛的呢?我們先來看下上述代碼中的PropertyModifyingBeanDefinitionDecorator。

private static class PropertyModifyingBeanDefinitionDecorator implements BeanDefinitionDecorator {

   @Override
   public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
      Element element = (Element) node;
      //1.獲取BeanDefinition
      BeanDefinition def = definition.getBeanDefinition();

      MutablePropertyValues mpvs = (def.getPropertyValues() == null) ? new MutablePropertyValues() : def.getPropertyValues();
      mpvs.add("name", element.getAttribute("name"));
      mpvs.add("age", element.getAttribute("age"));

      ((AbstractBeanDefinition) def).setPropertyValues(mpvs);
      return definition;
   }
}

從decorate方法內(nèi)部看出這個decorator是用來給我們的BeanDefinition來添加屬性的。這樣一來我們就可以在Xml配置中定義元素的屬性值,比如下圖示例:

<?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:test="http://www.john.com/resource"
      xmlns:util="http://www.springframework.org/schema/util"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
       http://www.john.com/resource http://www.john.com/resource/org/wonder/frame/customBean/CustomXmlApplicationContext.xsd"
   default-lazy-init="true">
   <test:testBean id="testBean" name="Rob Harrop" age="23"/>
   <bean id="customisedTestBean" class="org.wonder.frame.customBean.CustomBean">
      <!-- 自定義標(biāo)簽加 自定義屬性 -->
      <test:set name="John wonder" age="36"/>
   </bean>

</beans>

我們看到testBean這個自定義標(biāo)簽定義了兩個屬性name和age。之后我們在使用這個testBean的時候就可以獲取到它的name和age屬性了。

CustomBean bean = (CustomBean) beanFactory.getBean("testBean");
System.out.println("name is:" +bean.getName() +" and age is:"+ bean.getAge());

那么ObjectNameBeanDefinitionDecorator這個attribute的Decorator是干嘛的呢?看如下示例

<!--為bean設(shè)置自定義Attr-->
<bean id="decorateWithAttribute" class="org.springframework.tests.sample.beans.TestBean" test:object-name="foo"/>

我們可以為這個Bean添加自定義Attribute,那么添加了這個Attribute我們怎么使用呢?看如下示例:

BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition("decorateWithAttribute");
assertEquals("foo", beanDefinition.getAttribute("objectName"));

我們通過BeanDefinition的getAttribute就能獲取到這個attribute值。

從Spring源碼得知BeanDefinition擴(kuò)展了AttributeAccessor接口,這個接口是用于附加和訪問Bean元數(shù)據(jù)的通用的接口。直接實現(xiàn)這個接口的是AttributeAccessorSupport類。這個類里定義了名為attributes 的LinkedHashMap。

Spring自定義Xml標(biāo)簽的使用方法

總結(jié)

Spring通過自定義標(biāo)簽和自定義屬性實現(xiàn)了很多擴(kuò)展功能,很多我們常用的Spring配置內(nèi)部都是通過它來完成的。

到此,相信大家對“Spring自定義Xml標(biāo)簽的使用方法”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI