This post is the third in a series of posts showing examples of registering a custom property source in Spring 3.1, where the property source requires non-trivial initialization of its own. Part 1 showed initialization of a stand-alone application, and Part 2 showed initialization of integration tests. This part will show how to initialize a custom property source in a Spring MVC web application.
Spring 3.1 introduced a very convenient hook for customizing the application context in a Spring web application - the ApplicationContextInitializer interface. An ApplicationContextInitializer can be used to set active profiles and register custom property sources, among other things.
Here is an example of an ApplicationContextInitializer that registers the RedisPropertySource introduced in Part 1.
Just like in the stand-alone example from Part 1, an ApplicationContext is created and initialized in order to wire up the components of the custom property source. This example uses the same property-source-context.xml configuration file from Part 1.
The ApplicationContextInitializer is registered with the Spring MVC servlet by adding a stanza to the web.xml file like this:
An alternative to adding the context-param stanza to web.xml is to implement a WebApplicationInitializer and add the ApplicationContextInitializer programmatically.
The JavaDoc for WebApplicationInitializer is a great source of documentation on programmatically configuring the servlet context. In this example, most of the servlet context configuration is in web.xml, showing that the two approaches can be combined.
The last interesting part of this example is a Controller to show the property placeholder values injected into the GreetingService from Part 1:
For the sake of simplicity, this example just returns a String without using a view. Like with the stand-alone example, the values returned from the GreetingService are resolved against a properties file included with the project. These default values can be overridden by setting operating system environment variables, setting Java command line options, or by starting a Redis server as described in Part 1.
The code for all three parts of this series is available in a runnable project in GitHub. The GitHub project also shows all the configuration using Java config in addition to the XML config shown here.