最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring中的自定義NamespaceHandler詳解

 更新時間:2023年11月17日 10:45:21   作者:securitit  
這篇文章主要介紹了Spring中的自定義NamespaceHandler詳解,通常情況下,Spring生態(tài)圈提供的功能已足夠使用,但不排除特殊情況下,需要匹配特殊及復雜的業(yè)務情況,Spring提供了可擴展Schema支持,可以自定義命名空間進行配置及解析,需要的朋友可以參考下

前言

通常情況下,Spring生態(tài)圈提供的功能已足夠使用,但不排除特殊情況下,需要匹配特殊及復雜的業(yè)務情況。Spring提供了可擴展Schema支持,可以自定義命名空間進行配置及解析。

自定義NamespaceHandler流程

在這里插入圖片描述

自定義NamespaceHandler項目結構

在這里插入圖片描述

1) 設計自定義配置

設計配置包含id、name、sex、word、blob五個屬性,同步創(chuàng)建JavaBean,用于屬性載體。

package com.arhorchin.securitit.hello.bean;
/**
 * @author Securitit.
 * @note Introduce相關BEAN.
 */
public class HelloIntroduceBean {
    /**
     * id.
     */
    private String id;
    /**
     * 姓名.
     */
    private String name;
    /**
     * 性別.
     */
    private String sex;
    /**
     * 語言.
     */
    private String word;
    /**
     * 博客.
     */
    private String blob;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getWord() {
        return word;
    }
    public void setWord(String word) {
        this.word = word;
    }
    public String getBlob() {
        return blob;
    }
    public void setBlob(String blob) {
        this.blob = blob;
    }
}

2) 定義XSD,描述自定義配置

XSD文件是對JavaBean的描述,需要注意xsd:schema節(jié)點的xmlns和targetNamespace屬性,需為要定義的命名空間。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema xmlns="http://code.alibabatech.com/schema/hello"
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" 		    
    xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:tool="http://www.springframework.org/schema/tool"
	targetNamespace="http://code.alibabatech.com/schema/hello">

	<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
	<xsd:import namespace="http://www.springframework.org/schema/beans" />
	<xsd:import namespace="http://www.springframework.org/schema/tool" />
	
	<xsd:complexType name="baseHelloType">
	</xsd:complexType>

	<xsd:complexType name="baseReferenceType">
	</xsd:complexType>

	<!-- 簡介節(jié)點定義. -->
	<xsd:element name="introduce">
		<xsd:complexType>
			<xsd:complexContent>
				<xsd:extension base="baseHelloType">
					<xsd:attribute name="id" type="xsd:string">
						<xsd:annotation>
							<xsd:documentation>
								id.
							</xsd:documentation>
						</xsd:annotation>
					</xsd:attribute>
					<xsd:attribute name="name" type="xsd:string">
						<xsd:annotation>
							<xsd:documentation>
								名稱.
							</xsd:documentation>
						</xsd:annotation>
					</xsd:attribute>
					<xsd:attribute name="sex" type="xsd:string">
						<xsd:annotation>
							<xsd:documentation>
								性別.
							</xsd:documentation>
						</xsd:annotation>
					</xsd:attribute>
					<xsd:attribute name="word" type="xsd:string">
						<xsd:annotation>
							<xsd:documentation>
								語言.
							</xsd:documentation>
						</xsd:annotation>
					</xsd:attribute>
					<xsd:attribute name="blob" type="xsd:string">
						<xsd:annotation>
							<xsd:documentation>
								博客.
							</xsd:documentation>
						</xsd:annotation>
					</xsd:attribute>
				</xsd:extension>
			</xsd:complexContent>
		</xsd:complexType>
	</xsd:element>

	<!-- 代理對象設置. -->
	<xsd:element name="reference">
		<xsd:complexType>
			<xsd:complexContent>
				<xsd:extension base="baseReferenceType">
					<xsd:attribute name="id" type="xsd:string">
						<xsd:annotation>
							<xsd:documentation>
								see document
							</xsd:documentation>
						</xsd:annotation>
					</xsd:attribute>
					<xsd:attribute name="interface" type="xsd:string">
						<xsd:annotation>
							<xsd:documentation>
								see document
							</xsd:documentation>
						</xsd:annotation>
					</xsd:attribute>
				</xsd:extension>
			</xsd:complexContent>
		</xsd:complexType>
	</xsd:element>
</xsd:schema> 

3) 創(chuàng)建Handler

創(chuàng)建Handler,繼承NamespaceHandlerSupport,配置解析器

Handler的實現比較簡單,主要目的是將自定義配置與解析器Parser進行綁定,同時指定配置屬性載體JavaBean。

package com.arhorchin.securitit.hello.handler;

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

import com.arhorchin.securitit.hello.bean.HelloIntroduceBean;
import com.arhorchin.securitit.hello.parser.IntroduceReqBeanDefinitionParser;

/**
 * @author Securitit.
 * @note Spring namespace定義.
 */
public class HelloNamespaceHandler extends NamespaceHandlerSupport {

    @Override
    public void init() {
        registerBeanDefinitionParser("introduce", new IntroduceReqBeanDefinitionParser(HelloIntroduceBean.class, true));
    }

}

4) 創(chuàng)建Parser

創(chuàng)建Parser,繼承BeanDefinitionParser,解析配置屬性。

Parser負責接收配置屬性值,對屬性值進行校驗處理,并初始化RootBeanDefinition,設置Bean相關屬性。

package com.arhorchin.securitit.hello.parser;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

/**
 * @author Securitit.
 * @note 解析Spring的XML文件, 設置Bean信息.
 */
public class IntroduceReqBeanDefinitionParser implements BeanDefinitionParser {

    /**
     * BEAN類型.
     */
    private final Class<?> beanClass;

    /**
     * 是否必需.
     */
    private final boolean required;

    /**
     * constructor.
     * @param beanClass .
     * @param required .
     */
    public IntroduceReqBeanDefinitionParser(Class<?> beanClass, boolean required) {
        this.beanClass = beanClass;
        this.required = required;
    }

    protected Class<?> getBeanClass(Element element) {
        return beanClass;
    }

    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        return parse(element, parserContext, beanClass, required);
    }

    /**
     * Bean解析.
     * @param element 當前正在解析元素.
     * @param parserContext 解析器上下文.
     * @param beanClass 正在解析的Bean類.
     * @param required 是否必需.
     * @return 返回解析Bean定義.
     */
    private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass,
            boolean required) {
        String id = null;
        String name = null;
        String sex = null;
        String word = null;
        String blob = null;
        RootBeanDefinition beanDefinition = null;

        // 取introduce元素屬性值.
        id = element.getAttribute("id");
        name = element.getAttribute("name");
        sex = element.getAttribute("sex");
        word = element.getAttribute("word");
        blob = element.getAttribute("blob");

        // 檢查id值域.
        if (StringUtils.isEmpty(id)) {
            throw new IllegalStateException("hello:introduce元素屬性id值必需.");
        }
        // 檢查name值域.
        if (StringUtils.isEmpty(name)) {
            throw new IllegalStateException("hello:introduce元素屬性name值必需.");
        }
        // 檢查sex值域.
        if (StringUtils.isNotEmpty(sex) && !"male".equals(sex) && !"female".equals(sex)) {
            throw new IllegalStateException("hello:introduce元素屬性sex值若存在,需為male或female.");
        }

        // 設置Bean定義.
        beanDefinition = new RootBeanDefinition();
        beanDefinition.setBeanClass(beanClass);
        beanDefinition.setLazyInit(false);
        parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
        beanDefinition.getPropertyValues().addPropertyValue("id", id);
        beanDefinition.getPropertyValues().addPropertyValue("name", name);
        beanDefinition.getPropertyValues().addPropertyValue("sex", sex);
        beanDefinition.getPropertyValues().addPropertyValue("word", word);
        beanDefinition.getPropertyValues().addPropertyValue("blob", blob);
        return beanDefinition;
    }

}

5) 配置spring.handlers和spring.schemas文件

spring.handlers文件內容:

http\://code.alibabatech.com/schema/hello=com.arhorchin.securitit.hello.handler.HelloNamespaceHandler

spring.schemas文件內容:

http\://code.alibabatech.com/schema/hello/hello.xsd=META-INF/hello.xsd

6) 在Spring配置中進行應用

在應用中增加配置,引入對應的命名空間,并配置元素內容。

<?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:hello="http://code.alibabatech.com/schema/hello"
	xsi:schemaLocation="http://www.springframework.org/schema/beans        
    http://www.springframework.org/schema/beans/spring-beans.xsd        
    http://code.alibabatech.com/schema/hello       
    http://code.alibabatech.com/schema/hello/hello.xsd">
    
    <hello:introduce id="securitit" name="Securitit" sex="male" word="Java" blob="https://blog.csdn.net/securitit?spm=1001.2100.3001.5343"/>
    
</beans>

通過JUnit進行測試加載配置文件,進行測試。

package com.arhorchin.securitit.component;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.arhorchin.securitit.hello.bean.HelloIntroduceBean;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
        locations = { "classpath:spring/applicationContext.xml" })
public class NamespaceHandlerTest {

    /**
     * logger.
     */
    private Logger logger = LoggerFactory.getLogger(NamespaceHandlerTest.class);

    @Autowired
    private HelloIntroduceBean helloIntroduceBean;

    @Test
    public void test() {
        logger.info("Spring NamespaceHandler 自定義測試.");

        logger.info("hello:introduce元素屬性:[id=" + helloIntroduceBean.getId() + "], [name=" + helloIntroduceBean.getName()
                + "], [sex=" + helloIntroduceBean.getSex() + "], [word=" + helloIntroduceBean.getWord() + "], [blob="
                + helloIntroduceBean.getBlob() + "]");
    }

}

可以看到,控制臺輸出了Spring配置文件中定義的內容。

2021-01-28 16:38:58 INFO [com.arhorchin.securitit.component.NamespaceHandlerTest] Spring NamespaceHandler 自定義測試.
2021-01-28 16:38:58 INFO [com.arhorchin.securitit.component.NamespaceHandlerTest] hello:introduce元素屬性:[id=securitit], [name=Securitit], [sex=male], [word=Java], [blob=https://blog.csdn.net/securitit?spm=1001.2100.3001.5343]

總結

自定義NamespaceHandler的需求是會有很大幾率碰見的,當然,在不知道的情況下,可能會選擇其他方案,這就需要多了解,以便在需要的時候做出正確的選擇。

源碼解析基于spring-framework-5.0.5.RELEASE版本源碼。

若文中存在錯誤和不足,歡迎指正!

到此這篇關于Spring中的自定義NamespaceHandler詳解的文章就介紹到這了,更多相關自定義NamespaceHandler內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 深入解析Mybatis中緩存機制及優(yōu)缺點

    深入解析Mybatis中緩存機制及優(yōu)缺點

    MyBatis緩存分為一級(SqlSession級,自動維護)和二級(Mapper級,需配置),通過減少數據庫訪問提升性能,但存在臟數據和分布式不兼容風險,適合高頻查詢低頻修改場景,需合理配置以平衡效率與一致性,本文給介紹Mybatis中緩存機制及優(yōu)缺點,感興趣的朋友跟隨小編一起看看吧
    2025-08-08
  • SpringBoot?容器刷新前回調ApplicationContextInitializer

    SpringBoot?容器刷新前回調ApplicationContextInitializer

    這篇文章主要為大家介紹了SpringBoot?容器刷新前回調ApplicationContextInitializer使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • MyBatisPlus利用Service實現獲取數據列表

    MyBatisPlus利用Service實現獲取數據列表

    這篇文章主要為大家詳細介紹了怎樣使用 IServer 提供的 list 方法查詢多條數據,這些方法將根據查詢條件獲取多條數據,感興趣的可以了解一下
    2022-06-06
  • Groovy的規(guī)則腳本引擎實例解讀

    Groovy的規(guī)則腳本引擎實例解讀

    這篇文章主要介紹了Groovy的規(guī)則腳本引擎實例解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • jOOQ串聯字符串拒絕使用的原因實例

    jOOQ串聯字符串拒絕使用的原因實例

    這篇文章主要為大家介紹了jOOQ串聯字符串拒絕使用的原因實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • Java單例模式與破壞單例模式概念原理深入講解

    Java單例模式與破壞單例模式概念原理深入講解

    單例模式(Singleton?Pattern)是?Java?中最簡單的設計模式之一。這種類型的設計模式屬于創(chuàng)建型模式,它提供了一種創(chuàng)建對象的最佳方式。這種模式涉及到一個單一的類,該類負責創(chuàng)建自己的對象,同時確保只有單個對象被創(chuàng)建
    2023-02-02
  • Java如何把map分割成多個map

    Java如何把map分割成多個map

    這篇文章主要介紹了Java如何把map分割成多個map,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2024-08-08
  • Java定時任務取消的示例代碼

    Java定時任務取消的示例代碼

    java定時任務如何取消,并比如,我之前想每周二晚上6點自動生成一條devops流水線,現在我想停掉,下面給大家分享java定時任務取消的示例代碼,演示如何創(chuàng)建一個每周二晚上6點自動生成一條devops流水線的定時任務,感興趣的朋友一起看看吧
    2024-02-02
  • SpringCloud之熔斷監(jiān)控Hystrix Dashboard的實現

    SpringCloud之熔斷監(jiān)控Hystrix Dashboard的實現

    這篇文章主要介紹了SpringCloud之熔斷監(jiān)控Hystrix Dashboard的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-09-09
  • Mybatis中@Param的用法和作用詳解

    Mybatis中@Param的用法和作用詳解

    這篇文章主要介紹了Mybatis中@Param的用法和作用,在文中給大家補充了spring中@param和mybatis中@param使用區(qū)別,需要的朋友可以參考下
    2017-09-09

最新評論

县级市| 清水河县| 南城县| 乐山市| 台南市| 岑溪市| 景洪市| 海伦市| 新竹县| 静海县| 淮安市| 团风县| 冷水江市| 古田县| 昌黎县| 姜堰市| 康马县| 长治市| 阜南县| 微山县| 富民县| 揭阳市| 桐乡市| 鄢陵县| 三门峡市| 黄山市| 万州区| 莱芜市| 时尚| 甘谷县| 同江市| 南川市| 米易县| 青浦区| 郓城县| 沈阳市| 鲁甸县| 德惠市| 日土县| 四平市| 新安县|