import java.util.Map;import org.apache.commons.configuration.ConfigurationException;import org.apache.commons.configuration.PropertiesConfiguration;import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;import org.apache.log4j.Logger;/** * * 設定檔properties自動載入類 * @author lyh * @version 2012-6-5 * @see PropertiesAutoLoad * @since */public class PropertiesAutoLoad{ /** * 日誌 */ private static final Logger log = Logger.getLogger(PropertiesAutoLoad.class); /** * Singleton */ private static final PropertiesAutoLoad AUTO_LOAD = new PropertiesAutoLoad(); /** * Configuration */ private static PropertiesConfiguration propConfig; /** * 自動儲存 */ private static boolean autoSave = true; /** * properties檔案路徑 * @param propertiesFile * @return * @see */ public static PropertiesAutoLoad getInstance(String propertiesFile) { //執行初始化 init(propertiesFile); return AUTO_LOAD; } /** * 根據Key獲得對應的value * @param key * @return * @see */ public Object getValueFromPropFile(String key) { return propConfig.getProperty(key); } /** * 獲得對應的value數組 * @param key * @return * @see */ public String[] getArrayFromPropFile(String key) { return propConfig.getStringArray(key); } /** * 設定屬性 * @param key * @param value * @see */ public void setProperty(String key, String value) { propConfig.setProperty(key, value); } /** * 設定屬性 * @param map * @see */ public void setProperty(Map<String, String> map) { for (String key : map.keySet()) { propConfig.setProperty(key, map.get(key)); } } /** * 構造器私人化 */ private PropertiesAutoLoad() { } /** * 初始化 * @param propertiesFile * @see */ private static void init(String propertiesFile) { try { propConfig = new PropertiesConfiguration(propertiesFile); //自動重新載入 propConfig.setReloadingStrategy(new FileChangedReloadingStrategy()); //自動儲存 propConfig.setAutoSave(autoSave); } catch (ConfigurationException e) { log.error(e.getMessage()); } } /** * Test * @param args * @see */ public static void main(String[] args) { log.info(PropertiesAutoLoad.getInstance("props/config/XX.properties").getValueFromPropFile( "pageSize")); }}