1. 在resource目录下创建META-INF
在META-INF目录下创建spring.hanlders: 指定NamespaceHandler;spring.schemas: 指定xsd模版文件. Spring 在初始化的时候,会自动到META-INF文件下扫描spring.handlers 和 spring.schemas文件
- spring.handlers (前面的key随意指定)
http\://www.test.com/schema/apple=com.webgroup.test.handlers.MyNameSpaceHandler
-spring.schemas(指定xsd文件路径)
http\://www.test.com/schema/apple.xsd=/custome-apple.xsd
2. 创建xsd文件
xmlns, targetNameSpace 指定的是在spring.handlers 中自定义的key
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.test.com/schema/apple"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.test.com/schema/apple">
<xsd:complexType name="apple">
<xsd:attribute name ="id" type="xsd:string"></xsd:attribute>
<xsd:attribute name="name" type="xsd:string"> </xsd:attribute>
</xsd:complexType>
<xsd:element name="apple" type="apple"></xsd:element>
</xsd:schema>
3. 创建NameSpaceHandler
public class MyNameSpaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("apple", new AppleBeanDefinitionParser());
}
}
NameSpaceHander管理着complexType 和 BeanDefinitionParser的一一对应关系。上文中指定的"apple" 要和xsd文件中定义的complexType名保持一致。
4. 创建BeanDefinitionParser
public class AppleBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
@Override
protected Class<?> getBeanClass(Element element) {
return Apple.class;
}
@Override
protected void doParse(Element element, BeanDefinitionBuilder builder) {
String id = element.getAttribute("id");
String name = element.getAttribute("name");
if (StringUtils.isNotEmpty(id)) {
builder.addPropertyValue("id", id);
}
if (StringUtils.isNotEmpty(name)) {
builder.addPropertyValue("name", name);
}
}
}
BeanDefinitionParser将属性值从文件里读出来,并写在BeanDefinitionBuilder中。
5. 测试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:mytest="http://www.test.com/schema/apple"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.test.com/schema/apple http://www.test.com/schema/apple.xsd">
<mytest:apple id="1234" name="nameTest"/>
</beans>
xsi:schemaLocation 指定的是spring官方、自定义的nameSpaceHandler和xds文件的路径;
6.测试类
@Controller
public class TestController {
@Autowired
private Apple apple;
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public String test() {
return apple.getName();
}
}
网友评论