1、工具类:
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
public class Config {
private static PropertiesConfiguration propConfig;
private static final Config CONFIG = new Config();
/**
* 自动保存
*/
private static boolean autoSave = true;
private Config() {
}
public static Config getInstance(String propertiesFile) {
//执行初始化
init(propertiesFile);
return CONFIG;
}
/**
* 初始化
*
* @param propertiesFile
* @throws ConfigurationException
* @see
*/
private static void init(String propertiesFile){
try {
propConfig = new PropertiesConfiguration(propertiesFile);
//自动重新加载
propConfig.setReloadingStrategy(new FileChangedReloadingStrategy());
//自动保存
propConfig.setAutoSave(autoSave);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据Key获得对应的value
*
* @param key
* @return
* @see
*/
public Object getValue(String key) {
return propConfig.getProperty(key);
}
/**
* 设置属性
*
* @param key
* @param value
* @see
*/
public void setProperty(String key, String value) {
propConfig.setProperty(key, value);
}
}
2、使用
String initConfigurationWhetherPath = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/initConfiguration.properties");
Config initConfigurationWhetherCg = Config.getInstance(initConfigurationWhetherPath);
initConfigurationWhetherCg.setProperty("initConfigurationWhether","1");
*.properties:
initConfigurationWhether=0
用此工具类修改多个properties时,一个properties对应一个propConfig对象,故需重新getInstance,目的是修改propConfig对象:
Config initConfigurationWhetherCg = Config.getInstance(initConfigurationWhetherPath);
initConfigurationWhetherCg.setProperty("initConfigurationWhether","1");
String saveImageYNPath = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/drive.properties");
Config saveImageYNCg = Config.getInstance(saveImageYNPath);
saveImageYNCg.setProperty("alarm.saveImage.yesOrNot",saveImage);