如何使用Spring自定義Xml標簽
前言
在早期基于Xml配置的Spring Mvc項目中,我們往往會使用<context:component-scan basePackage="">這種自定義標簽來掃描我們在basePackae配置里的包名下的類,并且會判斷這個類是否要注入到Spring容器中(比如這個類上標記了@Component注解就代表需要被Spring注入),如果需要那么它會幫助我們把這些類一一注入。
正文
在分析這個自定義標簽的解析機制前,我先提前劇透這個自定義標簽是通過哪個強大的類來解析的吧,就是隸屬于spring-context包下的ComponentScanBeanDefinitionParser,這個類在Springboot掃描Bean的過程中也扮演了重要角色。
既然知道了是這個類解析的,那么我們可以通過idea強大的搜索功能來搜它的引用之處了,這邊就截圖如下:
可以看到這里面初始化了8個帶Parser后綴的各種Parser,從方法registerBeanDefinitionParser看出Spring是通過這個ContextNamespaceHandler來完成對以<context:自定義命名空間開頭的標簽解析器的注冊。我們可以看到Spring內部已經集成了幾個常用的NamespaceHandler,截圖如下:
那么我們自己是否可以自定義一個NamespaceHandler來注冊我們自定義的標簽解析器呢?答案是肯定的。
自定義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.設置resolver reader.setNamespaceHandlerResolver(resolver); //3.設置驗證模式 reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); //4.設置entityResolver reader.setEntityResolver(new CustomSchemaResolver()); }
可以看到我們在初始化BeanDefinitionReader的時候我們可以設置NamespaceHandlerResolver并且配置它的NamespaceHandler文件路徑。那這個NamespaceHandler配置文件應該怎么寫呢?
http\://www.john.com/resource=org.wonder.frame.customBean.TestNamespaceHandler
就一行配置,但是這里有兩點要注意:
- http\://www.john.com/resource要和xsd的targetNamspace一致。
- http\://www.john.com/resource要和xml配置文件中的自定義namespace一致。
從代碼里看出來我們解析自定義標簽的時候其實是還需要自定義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設置了自定義的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接口,內部直接定義一個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.設置beanDefinition的 屬性 propertyValues definition.setPropertyValues(mpvs); //2.獲取到beanDefinition的 registry parserContext.getRegistry().registerBeanDefinition(element.getAttribute("id"), definition); return null; } }
PersonDefinitionParser繼承自AbstractSingleBeanDefinitionParser抽象類,內部使用BeanDefinitionBuilder構造器來完成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方法內部看出這個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"> <!-- 自定義標簽加 自定義屬性 --> <test:set name="John wonder" age="36"/> </bean> </beans>
我們看到testBean這個自定義標簽定義了兩個屬性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設置自定義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擴展了AttributeAccessor接口,這個接口是用于附加和訪問Bean元數(shù)據(jù)的通用的接口。直接實現(xiàn)這個接口的是AttributeAccessorSupport類。這個類里定義了名為attributes 的LinkedHashMap。
總結
Spring通過自定義標簽和自定義屬性實現(xiàn)了很多擴展功能,很多我們常用的Spring配置內部都是通過它來完成的。
以上就是如何使用Spring自定義Xml標簽的詳細內容,更多關于使用Spring自定義Xml標簽的資料請關注腳本之家其它相關文章!
- Springboot項目使用html5的video標簽完成視頻播放功能
- SpringBoot使用Thymeleaf自定義標簽的實例代碼
- springboot 自定義權限標簽(tld),在freemarker引用操作
- 這一次搞懂Spring自定義標簽以及注解解析原理說明
- SpringMVC form標簽引入及使用方法
- Spring Cloud體系實現(xiàn)標簽路由的方法示例
- spring boot 集成 shiro 自定義密碼驗證 自定義freemarker標簽根據(jù)權限渲染不同頁面(推薦
- springboot 在ftl頁面上使用shiro標簽的實例代碼
- Spring源碼解密之默認標簽的解析
- SpringMVC表單標簽知識點詳解
相關文章
Spring Security OAuth2 token權限隔離實例解析
這篇文章主要介紹了Spring Security OAuth2 token權限隔離實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11SpringBoot @ConfigurationProperties注解的簡單使用
即便現(xiàn)在簡化了配置,但是一個獨立的配置文件總是易于理解而且使人安心的。Spring在構建完項目后,會默認在resources文件夾下創(chuàng)建一個application.properties文件,application.yml也是一樣的效果。@ConfigurationProperties可以獲取配置文件中的數(shù)據(jù),將其注入類。2021-05-05