Sean Nguyen
Sean Nguyen

Reputation: 13168

load spring application context from string

Can somebody show me how to use Spring to load application context through xml string instead of file or classpath resource?

Thanks,

Upvotes: 6

Views: 5770

Answers (3)

Rajendra
Rajendra

Reputation: 1763

Haven't tried it so far but can probably give a try:

// 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/ Let me know if it works...

Upvotes: 0

Reza Aliakabri
Reza Aliakabri

Reputation: 111

Use this:

String contextXML = ...;
Resource resource = new ByteArrayResource(contextXML.getBytes());
GenericXmlApplicationContext springContext = new GenericXmlApplicationContext();
springContext.load(resource);
Object myBean = springContext.getBean("myBean");
...

Reza

Upvotes: 11

Sean Nguyen
Sean Nguyen

Reputation: 13168

i found a way doing it.

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

Upvotes: 3

Related Questions