Java动态读取properties配置文件,不需要重启服务。核心根据File.lastModified判断文件是否有变动,重新读取配置文件内容。
PropertiesUtil.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| package cn.joinhealth.interview.common.util;
import cn.joinhealth.celina.common.enums.FileTypeEnum; import cn.joinhealth.celina.common.utils.StringUtils; import lombok.extern.slf4j.Slf4j;
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.*;
@Slf4j public class PropertiesUtil { private static Properties prop;
private static Long lastModified = 0L;
private static final String HUG_INTERVIEW_ENV = "hug_interview"; private static final String SERVER_PROPERTIES_PATH = "/cfg/server/server.properties";
private static void init() { prop = new Properties(); try { String path = System.getenv(HUG_INTERVIEW_ENV); if (StringUtils.isBlank(path)) { path = System.getProperty(HUG_INTERVIEW_ENV); } FileInputStream in = new FileInputStream(path + SERVER_PROPERTIES_PATH); prop.load(in); in.close(); } catch (IOException e) { log.error("", e); } }
private static boolean isPropertiesModified() { boolean returnValue = false; String path = System.getenv(HUG_INTERVIEW_ENV); if (StringUtils.isBlank(path)) { path = System.getProperty(HUG_INTERVIEW_ENV); } File file = new File(path + SERVER_PROPERTIES_PATH); if (file.lastModified() > lastModified) { log.info("修改server.properties配置文件"); lastModified = file.lastModified(); returnValue = true; } return returnValue; }
public static String getPropertiesValue(String key) { if (prop == null || isPropertiesModified()) { init(); } String value; try { value = prop.getProperty(key); if (value != null) { value = value.trim(); } } catch (Exception e) { log.error("getperty:", e); return null; } return value; } }
|
java.io.File.lastModified()
该方法返回表示此抽象路径名的文件的最后修改时间。