有人可以告诉我如何使用Spring通过xml字符串而不是文件或类路径资源来加载应用程序上下文吗?
谢谢,
答案 0 :(得分:11)
使用此:
String contextXML = ...;
Resource resource = new ByteArrayResource(contextXML.getBytes());
GenericXmlApplicationContext springContext = new GenericXmlApplicationContext();
springContext.load(resource);
Object myBean = springContext.getBean("myBean");
...
礼
答案 1 :(得分:3)
我找到了一种方法。
public MyApplicationContext(String xml,
ApplicationContext parent){
super(parent);
this.configResources = new Resource[1];
configResources[0] = new ByteArrayResource(xml.getBytes());
refresh();
}
private Resource[] configResources;
protected Resource[] getConfigResources() {
return this.configResources;
}
答案 2 :(得分:0)
到目前为止还没试过,但可以尝试一下:
// define and open the input stream from which we read the configuration
InputStream input = new ByteArrayInputStream("string".getBytes("UTF-8"));
// create the bean factory
DefaultListableBeanFactory beans = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beans);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
reader.loadBeanDefinitions(new InputStreamResource(input));
beans.preInstantiateSingletons();
input.close();
@Ref:http://beradrian.wordpress.com/2010/03/30/load-spring-from-input-stream/ 让我知道它是否有效......