Using PropertySource & Environment
PropertySource and Environment was added to Spring 3.1, these classes simplify working with properties. In Spring 3.2 MockEnvironment and MockPropertySource were also added making it much easier to mock properties in tests. As the existing approach was not removed (just slightly updated) there are now several ways to use and configure the use of properties in Spring. I wrote this article to explain the options not least because at the moment this topic doesn't seem to be covered fully on the internet.
For a working example in code of these techniques see the github project https://github.com/jamesdbloom/base_spring_mvc_web_application
Before Spring 3.1 the only way to register a properties file was by:
<context:property-placeholder location="some.properties"/>
In Spring 3.1 the @PropertySource annotation was introduced in JavaConfig as follows:
@Configuration @PropertySource("classpath:some.properties") public class ApplicationConfiguration
In addition, from Spring 3.1, the underlying object created by using <context:property-placeholder> is a new class called PropertySourcesPlaceholderConfigurer. This new object is more flexible and now interacts with Environment and PropertySource both also introduced in Spring 3.1.
Note: to understand how this XML tag drives the addition of a PropertySourcesPlaceholderConfigurer to the ApplicationContext see ContextNamespaceHandler and PropertyPlaceholderBeanDefinitionParser in org.springframework.context.config.
In Spring 3.2 two new classes where introduced to support mocking properties these are MockEnvironment and MockPropertySource. Environment and PropertySources are used during bean creation so any mock versions needs to be added into the ApplicationContext before bean creation, this was not previously easy. To solve this the @ContextConfiguration was extended to add support for an ApplicationContextInitializer to provide access to the Environment and PropertySource in the ApplicationContext prior to bean creation, as shown below.
For a working example in code of the techniques below see the github project https://github.com/jamesdbloom/base_spring_mvc_web_application
Read full article from Using PropertySource & Environment