利用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");

猜你喜欢

转载自blog.csdn.net/u010760374/article/details/81111698