简体   繁体   English

如何在Spring 2.5中从字符串加载应用程序上下文?

[英]How to load application context from string in Spring 2.5?

As the title says, I want to load some beans from a String. 如标题所示,我想从字符串中加载一些bean。 This approach only works in Spring 3 because GenericXmlApplicationContext is unavailable in version 2.5. 该方法仅在Spring 3中有效,因为GenericXmlApplicationContext在2.5版中不可用。

I have not tested it myself, but according to the API documentation , you can easily extend the AbstractXmlApplicationContext and implement the getConfigResources() method. 我没有亲自测试过,但是根据API文档 ,您可以轻松扩展AbstractXmlApplicationContext并实现getConfigResources()方法。 You can use the org.springframework.core.io.ByteArrayResource to serve as a placeholder for your XML string. 您可以使用org.springframework.core.io.ByteArrayResource充当XML字符串的占位符。

Use the approach outlined here . 使用此处概述的方法。 With one additional step, pass the DefaultListableBeanFactory into a GenericApplicationContext (this one has been around since Spring 1.1 and the GenericXmlApplicationContext is basically a convenience class doing more or less the same as in that blog post). 再增加一个步骤,将DefaultListableBeanFactory传递到GenericApplicationContext (自Spring 1.1以来就存在,而GenericXmlApplicationContext本质上是一种便利类,与该博客文章大致相同)。

So something like this should work 所以这样的事情应该工作

String content = ...
GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);
reader.loadBeanDefinitions(new ByteArrayResource(content.getBytes())); 
ctx.refresh();

The ApplicationContext should now be ready for use. 现在应该可以使用ApplicationContext了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM