您的位置:首页 > 编程语言 > Java开发

如何在java对象里访问Spring中已加载的property内容

2014-08-19 00:00 471 查看

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;
03
04         @Override
05         protected void processProperties(ConfigurableListableBeanFactory beanFactory,
06                   Properties props)  throws BeansException {
07              super .processProperties(beanFactory, props);
08
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()));
14              }
15          }
16
17          public static String getProperty(String name) {
18              return propertiesMap.get(name);
19          }
20     }

Of course, we could run into problems if a class tries to use PropertiesUtil before 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 source
print
?

< context-param >
< param-name >contextConfigLocation</ param-name >
< param-value >
/WEB-INF/applicationContext.xml
</ param-value >
</ context-param >

< listener >
< listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class >
</ listener >
<!-- Other listeners -->


http://www.jdocs.com/spring/1.2.8/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html

http://j2eecookbook.blogspot.com/2007/07/accessing-properties-loaded-via-spring.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐