Custom xsd file operation in Spring

1 set the syntax format of html file xsd file

Write xsd file according to the properties of POJO.

for example

<?xml version="1.0" encoding="UTF-8" ?>
<schema xmlns=""

    <element name="user">
            <attribute name="id" type="string" />
            <attribute name="name" type="string" />
            <attribute name="email" type="string" />

The corresponding POJO is

public class User {
    private String name;
    private String email;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String getEmail() {
        return email;
    public void setEmail(String email) { = email;

Property's getter and setter methods are indispensable

The User's properties can be configured in xml, such as

<beans xmlns=""

    <mytest:user id="testBean"  name="aaa" email="bbb"/>


mytest: is a custom namespace name classpath: is the local xsd file loading protocol

2 implement BeanDefinitionParser interface and extension class NamespaceHandlerSupport

Extend NamespaceHandlerSupport class: implement manual loading of data in XML into BeanDefinitionBuilder

public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {

    protected Class getBeanClass(Element element){
        return User.class;
    protected void doParse(Element element, BeanDefinitionBuilder bean) {
        String userName = element.getAttribute("name");
        String email = element.getAttribute("email");

        if(StringUtils.hasText(userName)) {
            bean.addPropertyValue("name", userName);

        if (StringUtils.hasText(email)) {
            bean.addPropertyValue("email", email);

Implement BeanDefinitionParser interface: manually register POJO's manual resolution results

public class MyNamespaceHandler extends NamespaceHandlerSupport {
    public void init() {
        registerBeanDefinitionParser("user",new UserBeanDefinitionParser());

3 set the Spring.handlers and Spring.schemas files

To configure META-INF/Spring.handlers:


When quoted When uses MyNamespaceHandler to resolve the reference object

Configure META-INF/Spring.schemas


Load custom xsd file

Access XML file of custom xsd configuration through ClassPathXmlApplicationContext

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Keywords: Programming Spring xml Attribute encoding

Added by pleigh on Wed, 16 Oct 2019 17:33:00 +0300