Home > Software > Programatically load Spring configuration from input stream

Programatically load Spring configuration from input stream

Some will argue about the utility of it, but I think Spring IoC is a powerful configuration tool and it makes sense. You can have a shared configuration across a network which can change over time.
In this case you can easily create a bean factory/application context which will serve as your application configuration object.
Without any further introduction, here’s the code:

	// define and open the input stream from which we read the configuration
	InputStream input = ... ;
	// create the bean factory
	DefaultListableBeanFactory beans = new DefaultListableBeanFactory(applicationContext);
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beans);
	reader.loadBeanDefinitions(new InputStreamResource(input));

DefaultListableBeanFactory can be replaced with GenericApplicationContext or any similar.
There are two lines that are mandatory


for setting the validation mode instead of AUTO to XSD, as this cannot be automatically detected when working with streams and


without which the beans created using a factory will not be instantiated.
The solution is pretty simple and straightforward, but if you’re not a Spring expert, it might take a while until you’ll discover it yourself.

Categories: Software Tags:
  1. June 14, 2010 at 11:36 am

    nice share,,,

  2. July 9, 2010 at 11:03 am

    This a very nice share, it helps creating XML configuration at runtime and create a new application context.
    There is an other solution:
    Dynamically create beans and register them inside a DefaultListableBeanFactory.
    code is like this:

    String[] parentConf = {};
    bstractApplicationContext parentContext = new FileSystemXmlApplicationContext(parentConf,true);
    DefaultListableBeanFactory parentLbf = (DefaultListableBeanFactory) parentContext.getBeanFactory();


  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: