ITeye博客

spring的xml string applicationcontext实现

macrochen · 2013-03-06 07:26 · Spring · 开源软件 · Markdown

这里有两种实现方式:


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;

/**
* 字符串形式的Spring ApplicationContext实现。
* 支持动态订阅spring配置的处理
*
* @author linxuan
*
*/
public class StringXmlApplicationContext extends AbstractXmlApplicationContext {
     private Resource[] configResources;

     public StringXmlApplicationContext(String stringXml) {
          this(new String[] { stringXml }, null);
     }

     public StringXmlApplicationContext(String[] stringXmls) {
          this(stringXmls, null);
     }

     public StringXmlApplicationContext(String[] stringXmls, ApplicationContext parent) {
          super(parent);
          this.configResources = new Resource[stringxmls.length];
          for (int i = 0; i < stringXmls.length; i++) {
               this.configResources[i] = new ByteArrayResource(stringXmls[i].getBytes());
          }
          refresh();
     }

     protected Resource[] getConfigResources() {
          return this.configResources;
     }
}

另外一种:


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.core.io.ByteArrayResource;

import java.io.IOException;

public class StringXmlApplicationContext extends AbstractXmlApplicationContext {

    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 必须是UTF-8编码的XML,即XML的第一行必须是<?xml version="1.0" encoding="UTF-8"?>
     */
    private String xml;

    public StringXmlApplicationContext(String xml) {
        this.xml = xml;
        refresh();
    }

    @Override
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
        byte[] bytes = xml.getBytes(DEFAULT_CHARSET);
        ByteArrayResource resource = new ByteArrayResource(bytes);
        reader.loadBeanDefinitions(resource);
    }

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。