记录一下properties文件读取(spring方式)

spring配置:

<!--自定义类-->   
 <bean id="configProperties" class="com.vimtech.bms.webchat.commom.util.PropertiesUtil">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="ignoreResourceNotFound" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:properties/*.properties</value>
            </list>
        </property>
        <property name="fileEncoding">
            <value>UTF-8</value>
        </property>
    </bean>
PropertiesUtil实现类
package com.vimtech.bms.webchat.commom.util;


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

import com.vimtech.exception.BaseException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Desc:properties配置文件读取类
 */
public class PropertiesUtil extends PropertyPlaceholderConfigurer {

    private static Map<String,String> ctxPropMap;
    @Override
    public void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props){
        super.processProperties(beanFactoryToProcess, props);
        ctxPropMap = new HashMap();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = String.valueOf(props.get(keyStr));
            ctxPropMap.put(keyStr, getPropertiesValuesStr(value,props));
        }
    }
    public static String getCtxProp(String name) {
        return ctxPropMap.get(name);
    }

    public static Map<String, String> getCtxPropMap() {
        return ctxPropMap;
    }
    
    /*
     * 获取模板的匹配项,生成一个集合
     */
    private String getPropertiesValuesStr(String value, Properties props) {
          Pattern p = Pattern.compile("\\$\\{(.*?)\\}");
          Matcher m = p.matcher(value);
          List<String> list = new ArrayList<String>();
          while (m.find()) {
              String str = String.valueOf(props.get(m.group(1)));
              if (str==null) {
                  throw new BaseException("properties文件key"+m.group(1)+"不存在!");
              }
              value = value.replaceFirst("\\$\\{(.*?)\\}",str);
          }
        return value; 
    }
}

在这块做了一个正则匹配方式${key}  会匹配到其他地方引用过的value

如:

WX.URL=fmsApp
WEBAPP.NAME=fms
WX.AUTHUSER=${WX.URL}/${WEBAPP.NAME}

posted @ 2019-03-11 16:36  升级打怪猴  阅读(522)  评论(0编辑  收藏  举报