disconf可以配置reload,當更改配置時自動刷新classpath下的配置文件。然而獲取最新的值官方說明是加@DisconfFileItem註解放在屬性的方法上,底層通過攔截器獲取的。
但是每個屬性都要定義一個屬性,其實是一件很繁瑣的事情。
所以,以下提供一種非官方實時獲取最新值的方式。
1 public class PropertiesUtils { 2 private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class); 3 private static final String charset = "UTF-8"; 4 private static final Properties sysProp = new Properties(); 5 private static long lastModify = 0L; 6 private static File system; 7 private PropertiesUtils() { 8 throw new IllegalAccessError("Utility class"); 9 } 10 static { 11 try { 12 system = new ClassPathResource("system.properties").getFile(); 13 load(system.lastModified()); 14 } catch (Exception e) { 15 logger.error("properties file load error",e); 16 throw new VmapRuntimeException(e); 17 } 18 } 19 20 private static void load(long updateTime) { 21 try { 22 //注意清空,否則沒有新值,會使用舊值 23 sysProp.clear(); 24 //獲取屬性 25 sysProp.load(new InputStreamReader(new FileInputStream(system), charset)); 26 //獲取文件修改時間 27 lastModify = updateTime; 28 } catch (IOException e) { 29 throw new RuntimeException(e); 30 } 31 } 32 33 34 /**獲取屬性配置值 35 * @param name 名稱 36 * @return 37 */ 38 public static String getProp(String name) { 39 long modify = system.lastModified(); 40 if (modify > lastModify) load(modify); 41 return sysProp.getProperty(name); 42 } 43 }
這樣獲取配置就不需要每個都定義一個屬性了。