表明PropertyPlaceholderConfigurer是承担properties读取任务的类。

 

下面的类继承PropertyPlaceholderConfigurer,通过重写processProperties方法把properties暴露出去了。

 

Java代码  收藏代码

  1. import java.util.HashMap;  

  2. import java.util.Map;  

  3. import java.util.Properties;  

  4.   

  5. import org.springframework.beans.BeansException;  

  6. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;  

  7. import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;  

  8.   

  9. public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer {  

  10.   

  11.     private static Map<String, Object> ctxPropertiesMap;  

  12.   

  13.     @Override  

  14.     protected void processProperties(ConfigurableListableBeanFactory beanFactory,  

  15.             Properties props)throws BeansException {  

  16.   

  17.         super.processProperties(beanFactory, props);  

  18.         //load properties to ctxPropertiesMap  

  19.         ctxPropertiesMap = new HashMap<String, Object>();  

  20.         for (Object key : props.keySet()) {  

  21.             String keyStr = key.toString();  

  22.             String value = props.getProperty(keyStr);  

  23.             ctxPropertiesMap.put(keyStr, value);  

  24.         }  

  25.     }  

  26.   

  27.     //static method for accessing context properties  

  28.     public static Object getContextProperty(String name) {  

  29.         return ctxPropertiesMap.get(name);  

  30.     }  

  31. }  

 

这样此类即完成了PropertyPlaceholderConfigurer的任务,同时又提供了上下文properties访问的功能。

于是在Spring配置文件中把PropertyPlaceholderConfigurer改成CustomizedPropertyConfigurer

 

Xml代码  收藏代码

  1. <!-- use customized properties configurer to expose properties to program -->  

  2. <bean id="configBean"   

  3.     class="com.payment.taobaoNavigator.util.CustomizedPropertyConfigurer">  

  4.     <property name="location" value="classpath:dataSource.properties" />  

  5. </bean>  

 

最后在程序中我们便可以使用CustomizedPropertyConfigurer.getContextProperty()来取得上下文中的properties的值了。



  1. #生成文件的保存路径  

  2. file.savePath = D:/test/  

  3. #生成文件的备份路径,使用后将对应文件移到该目录  

  4. file.backupPath = D:/test bak/  


ConfigInfo.java 中对应代码: 

Java代码  收藏代码

  1. @Component("configInfo")  

  2. public class ConfigInfo {  

  3.     @Value("${file.savePath}")  

  4.     private String fileSavePath;  

  5.   

  6.     @Value("${file.backupPath}")  

  7.     private String fileBakPath;  

  8.           

  9.     public String getFileSavePath() {  

  10.         return fileSavePath;  

  11.     }  

  12.   

  13.     public String getFileBakPath() {  

  14.         return fileBakPath;  

  15.     }      

  16. }  


业务类bo中使用注解注入ConfigInfo对象: 

Java代码  收藏代码

  1. @Autowired  

  2. private ConfigInfo configInfo;  


需在bean.xml中添加组件扫描器,用于注解方式的自动注入: 

Xml代码  收藏代码

  1. <context:component-scan base-package="com.my.model" />