spring的xml string applicationcontext實現

這裏有兩種實現方式:

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

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章