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

本文介绍如何通过扩展Spring的PropertyPlaceholderConfigurer类来创建一个名为PropertiesUtil的工具类,以便于在Java类中更方便地访问配置属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 }

If we now update the applicationProperties bean to use the PropertiesUtil class, 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 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.

01 < context-param >
02      < param-name >contextConfigLocation</ param-name >
03      < param-value >
04          /WEB-INF/applicationContext.xml
05      </ param-value >
06 </ context-param >
07  
08 < listener >
09      < listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class >
10 </ listener >
11  
12 <!-- Other listeners -->

References

  1. http://www.jdocs.com/spring/1.2.8/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html
  2. http://j2eecookbook.blogspot.com/2007/07/accessing-properties-loaded-via-spring.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值