1. 程式人生 > >Spring用程式碼來讀取properties檔案

Spring用程式碼來讀取properties檔案

我們都知道,Spring可以@Value的方式讀取properties中的值,只需要在配置檔案中配置org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location">
          <value>
classpath:config.properties</value> </property> </bean>

那麼在需要用到這些獲取properties中值的時候,可以這樣使用

    @Value("${db.name}")
    private String dbName;

但是這有一個問題,我每用一次配置檔案中的值,就要宣告一個區域性變數。有沒有用程式碼的方式,直接讀取配置檔案中的值。

答案就是重寫PropertyPlaceholderConfigurer

package com.utils;

import org.springframework.beans.BeansException;
import
org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Created by yd on 2017/3/30. */ public class PropertyPlaceholder extends
PropertyPlaceholderConfigurer{
private static Map<String,String> propertyMap; @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); propertyMap = new HashMap<>(); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); propertyMap.put(keyStr, value); } } //static method for accessing context properties public static Object getProperty(String name) { return propertyMap.get(name); } }

在配置檔案中,用上面的類,代替PropertyPlaceholderConfigurer

 <bean id="propertyConfigurer" class="com.gyoung.mybatis.util.PropertyPlaceholder">
     <property name="location">
         <value>classpath:config.properties</value>
     </property>
 </bean>

這樣在程式碼中就可以直接用程式設計方式獲取

 PropertyPlaceholder.getProperty("db.name");

如果是多個配置檔案,配置locations屬性

     <!--將多個配置檔案讀取到容器中,交給Spring管理-->
    <bean id="propertyConfigurer" class="com.utils.PropertyPlaceholder">
        <property name="locations">
            <list>
                <!-- 推薦使用file的方式引入,這樣可以將配置和程式碼分離 -->
                <value>classpath:/properties/*.properties</value>
                <value>classpath*:*.properties</value>
                <!--<value>classpath:/properties/mongodb.properties</value>-->
            </list>
        </property>
    </bean>