配置文件properties读取使用的好方法

  首先在spring配置文件applicationContext.xml中配置、

    <bean id="placeholderConfig"
          class="com.beikbank.common.utils.PropertyConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
                <value>classpath:redis.properties</value>
                <value>classpath:SysConfig.properties</value>
            </list>
        </property>
    </bean>

如果我们要在代码中使用SysConfig.properties中配置信息,我们可以自己写个类PropertyConfigurer继承PropertyPlaceholderConfigurer·

public class PropertyConfigurer 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);
        }
    }

    public static String getProperty(String name) {
        return propertyMap.get(name);
    }

    /**
     * 返回propertyMap
     *
     * @return
     */
    public static Map<String, String> getPropertyMap() {
        return propertyMap;
    }
}

这样把属性值在系统启动的时候就设进去可以后续直接调用静态方法了

原文地址:https://www.cnblogs.com/sky-chen/p/8529075.html