spring獲取值

表明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" />  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章