I’m working on an application library with a utility class called “Config” which is backed by the Spring Environment object and provides strongly typed getters for all the applications configuration values.
The property sources for the configuration can vary depending on environment (DEV/PROD) and usage (standalone/test/webapp), and can range from the default ones (system & env props) to custom database and JNDI sources.
What I’m struggling with is how to let the apps consuming this library easily configure the property source(s) used by Environment, such that the properties are available for use in our Config class and via the PropertySourcesPlaceholderConfigurer.
We’re still using XML configuration, so ideally this could be configured in XML something like.
<bean id="propertySources" class="...">
<property name="sources">
<list>
<ref local="jndiPropertySource"/>
<ref local="databasePropertySource"/>
</list>
</property>
</bean>
…and then injected somehow into the Environment’s property sources collection.
I’ve read that something like this may not be possible due to the timing of the app context lifecycle, and that this may need to be done using an application initializer class.
Any ideas?
I came up with the following which seems to work, but I’m fairly new to Spring, so I’m not so sure how it will hold up under different use cases.
Basically, the approach is to extend
PropertySourcesPlaceholderConfigurerand add a setter to allow the user to easily configure a List ofPropertySourceobjects in XML. After creation, the property sources are copied to the currentEnvironment.This basically allows the property sources to be configured in one place, but used by both placholder configuration and Environment.getProperty scenarios.
Extended
PropertySourcesPlaceholderConfigurerbeans.xml file showing basic configuration