利用Spring初始化加載多properties文件

一:首先創建一個屬性文件xxx.properties

 

二:然後自定義一個屬性加載類工具類,必須要extends PropertyPlaceholderConfigurer類,(實際是對PropertyPlaceholderConfigurer類的一個擴展)

public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer {

    private static Map<String, Object> ctxPropertiesMap;

    @Override
    protected void processProperties(
            ConfigurableListableBeanFactory beanFactoryToProcess,
            Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        ctxPropertiesMap = new HashMap<String, Object>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            ctxPropertiesMap.put(keyStr, value);
        }
    }

    public static Object getContextProperty(String name) {
        return ctxPropertiesMap.get(name);
    }

    public static Object setContextProperty(String name, Object value) {
        return ctxPropertiesMap.put(name, value);
    }

}

三:然後再spring文件中配置如下

<bean id="propertyConfigurer"
      class="com.ljzforum.platform.util.CustomizedPropertyConfigurer">
    <property name="locations">
        <list>
            <value>classpath:context/xxx.properties</value>
        </list>
    </property>
</bean> 

四:最後就是怎麼使用了,代碼如下

        String appId = (String) CustomizedPropertyConfigurer.getContextProperty("app_id");

        String app_secret =(String) CustomizedPropertyConfigurer.getContextProperty("app_secret");

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