Java 从字符串加载spring应用程序上下文
有人能告诉我如何使用Spring通过xml字符串而不是文件或类路径资源加载应用程序上下文吗Java 从字符串加载spring应用程序上下文,java,spring,Java,Spring,有人能告诉我如何使用Spring通过xml字符串而不是文件或类路径资源加载应用程序上下文吗 谢谢,到目前为止还没有尝试过,但可能可以尝试一下: // define and open the input stream from which we read the configuration InputStream input = new ByteArrayInputStream("string".getBytes("UTF-8")); // create the bean factory Defa
谢谢,到目前为止还没有尝试过,但可能可以尝试一下:
// 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();
@参考:
让我知道它是否有效…我找到了一种方法
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;
}
使用以下命令:
String contextXML = ...;
Resource resource = new ByteArrayResource(contextXML.getBytes());
GenericXmlApplicationContext springContext = new GenericXmlApplicationContext();
springContext.load(resource);
Object myBean = springContext.getBean("myBean");
...
Reza谢谢,它可以工作,但不是应用程序上下文。我需要一个应用程序上下文,以便可以用父上下文加载它。我终于想出了一种方法,你也可以内联完成:
GenericXmlApplicationContext springContext=newgenericXMLApplicationContext(newbytearrayresource(contextXML.getBytes())代码>+1谢谢!在MemoryResource中使用甚至更短:新的GenericXmlApplicationContext(新的InMemoryResource(contextXML))