美文网首页dubbo
基于spring-schema实现自定义配置

基于spring-schema实现自定义配置

作者: andersonoy | 来源:发表于2017-07-10 19:16 被阅读0次

基于spring-schema实现自定义配置

  • 痛点

    在很多情况下,我们需要为系统提供可配置化支持,简单的做法可以直接基于spring的标准Bean来配置,但配置较为复杂或者需要更多丰富控制的时候,会显得非常笨拙。
    一般的做法会用原生态的方式去解析定义好的xml文件,然后转化为配置对象,这种方式当然可以解决所有问题,但实现起来比较繁琐,特别是是在配置非常复杂的时候,解析工作是一个不得不考虑的负担
    Spring提供了可扩展Schema的支持,这是一个不错的折中方案

  • Demo(逆序看)

    • ApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");People p = (People)ctx.getBean("cutesource");
    • application.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:cutesource="http://blog.csdn.net/cutesource/schema/people" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://blog.csdn.net/cutesource/schema/people http://blog.csdn.net/cutesource/schema/people.xsd"> <cutesource:people id="cutesource" name="袁志俊" age="27"/>用了我们自定义的标签 </beans>
    • spring提供了spring.handlers和spring.schemas这两个配置文件来完成这项工作,放入META-INF文件夹中,地址必须是META-INF/spring.handlers和META-INF/spring.schemas,spring会默认去载入它们
    • 编写NamespaceHandler和BeanDefinitionParser完成解析工作
      • NamespaceHandlerSupport
        public class MyNamespaceHandler extends NamespaceHandlerSupport { public void init() { registerBeanDefinitionParser("people", new PeopleBeanDefinitionParser()); } }
      • AbstractSingleBeanDefinitionParser
        public class PeopleBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { protected Class getBeanClass(Element element) { return People.class; } protected void doParse(Element element, BeanDefinitionBuilder bean) { String name = element.getAttribute("name"); String age = element.getAttribute("age"); String id = element.getAttribute("id"); if (StringUtils.hasText(id)) { bean.addPropertyValue("id", id); } if (StringUtils.hasText(name)) { bean.addPropertyValue("name", name); } if (StringUtils.hasText(age)) { bean.addPropertyValue("age", Integer.valueOf(age)); } } }
      • 编写对应的xsd文件和JavaBean
  • References

相关文章

网友评论

    本文标题:基于spring-schema实现自定义配置

    本文链接:https://www.haomeiwen.com/subject/ggeuhxtx.html