Spring中的自定義NamespaceHandler詳解
前言
通常情況下,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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot?容器刷新前回調ApplicationContextInitializer
這篇文章主要為大家介紹了SpringBoot?容器刷新前回調ApplicationContextInitializer使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
SpringCloud之熔斷監(jiān)控Hystrix Dashboard的實現
這篇文章主要介紹了SpringCloud之熔斷監(jiān)控Hystrix Dashboard的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09

