Exposing the spring properties bean in java
To allow our Java classes to access the properties from the same
object as spring, we’ll need to extend the PropertyPlaceholderConfigurer
so that we can provide a more convenient method for retrieving the
properties (there is no direct method of retrieving properties!).
We can extend the spring provided class to allow us to reuse spring’s property resolver in our Java classes:
01
| public class PropertiesUtil
extends PropertyPlaceholderConfigurer {
|
02
|
private static Map propertiesMap;
|
05
|
protected void processProperties(ConfigurableListableBeanFactory beanFactory,
|
06
|
Properties props)
throws BeansException {
|
07
|
super
.processProperties(beanFactory, props);
|
09
|
propertiesMap =
new HashMap<String, String>();
|
10
|
for (Object key : props.keySet()) {
|
11
|
String keyStr = key.toString();
|
12
|
propertiesMap.put(keyStr, parseStringValue(props.getProperty(keyStr),
|
13
|
props,
new HashSet()));
|
17
|
public static String getProperty(String name) {
|
18
|
return propertiesMap.get(name);
|
If we now update the applicationProperties bean to use the
PropertiesUtilclass, we can use the static getProperty method to access
the resolved properties via the same object as the spring configuration
bean.
Of course, we could run into problems if a class tries to use
PropertiesUtilbefore the spring context has been initialised. For
example if you’re registering ServletContextListeners in your web.xml
before configuring spring, you’ll get a NullPointerException if one of
those classes tries to use PropertiesUtil. For that reason I’ve had to
declare the spring context before any context listeners.
view sourceprint?02
|
<
param-name
>contextConfigLocation</
param-name
>
|
04
|
/WEB-INF/applicationContext.xml
|
09
|
<
listener-class
>org.springframework.web.context.ContextLoaderListener</
listener-class
>
|
12
| <!-- Other listeners -->
|
References
http://www.jdocs.com/spring/1.2.8/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.htmlhttp://j2eecookbook.blogspot.com/2007/07/accessing-properties-loaded-via-spring.html