Spring extends XML tags

1. Define the configuration property Javabean
public class Person { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }}Copy the code
2. Provide an XSD file
<? The XML version = "1.0" encoding = "utf-8"? > <xsd:schema xmlns="http://soft1010.com/schema/demo" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:beans="http://www.springframework.org/schema/beans" targetNamespace="http://soft1010.com/schema/demo" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xsd:import namespace="http://www.springframework.org/schema/beans" /> <xsd:element name="person"> <xsd:complexType> <xsd:complexContent> <xsd:extension base="beans:identifiedType"> <xsd:attribute name="name" type="xsd:string" use="required" /> <xsd:attribute name="age" type="xsd:integer" use="required" /> </xsd:extension> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:schema>Copy the code
3. Write NamespaceHandler and BeanDefinitionParser to complete parsing
public class PersonBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {


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

    @Override
    protected void doParse(Element element, BeanDefinitionBuilder builder) {
        builder.addPropertyValue("name",element.getAttribute("name"));
        builder.addPropertyValue("age",element.getAttribute("age"));
        super.doParse(element, builder);
    }
}
Copy the code
public class PersonNamespaceHandlerSupport extends NamespaceHandlerSupport { @Override public void init() { registerBeanDefinitionParser("person",new PersonBeanDefinitionParser()); }}Copy the code
4. Write spring. Handlers and spring
http://soft1010.com/schema/demo=com.soft1010.xml.schema.spring.PersonNamespaceHandlerSupport
Copy the code
http://soft1010.com/schema/demo/Person.xsd=META-INF/Person.xsd
Copy the code
5, the application
public class Test { private static ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "spring.xml"); public static void main(String args[]){ Person person= (Person)context.getBean("person"); System.out.println(person.toString()); }}Copy the code

The prevalence of annotations, XML has been used very little and usefulness is low, put here for everyone to enjoy