---
title: "spring的xml string applicationcontext实现"
author: "macrochen"
date: "2013-03-06T07:26:31Z"
tags: []
categories: ["开源软件"]
slug: "spring-xml-string-applicationcontext"
draft: false
lastmod: "2013-03-06T07:26:31Z"
id: 1823024
url: "https://macrochen.iteye.com/blog/1823024"
---

这里有两种实现方式:

```xml

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;
     }
}

```


另外一种:

```xml

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);
    }

}

```