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.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); reader.loadBeanDefinitions(new InputStreamResource(input)); beans.preInstantiateSingletons(); input.close();
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.