Java ResourceBundle属性文件环境变量解析问题
解决方案
要解决properties文件中环境变量占位符不解析的问题,只需修改ApplicationResource枚举类,添加环境变量解析逻辑并在初始化时触发,无需改动任何调用getString的现有代码。
修改后的完整代码
public enum ApplicationResource { CONF_DIR_PATH("conf.dir.path"), DB_NAME("database.name"), FILE_SAVE_PATH("save.file.path"), // 更多枚举项 private final String value; ApplicationResource(String value) { this.value = value; } private static final String BUNDLE_NAME = "ApplicationResource"; private static Properties props; static { try { Properties defaults = new Properties(); initEnvironment(defaults, BUNDLE_NAME); props = new Properties(defaults); } catch (Throwable t) { t.printStackTrace(); } } private static void initEnvironment(Properties props, String bundleName) throws Throwable { ResourceBundle rb = ResourceBundle.getBundle(bundleName); Enumeration<?> enu = rb.getKeys(); String key = null; String value = null; while (enu.hasMoreElements()) { key = (String) enu.nextElement(); value = rb.getString(key); // 解析环境变量占位符后再存入Properties value = resolveEnvironmentVariables(value); props.setProperty(key, value); } } // 新增:解析字符串中的${ENV_VAR}格式占位符 private static String resolveEnvironmentVariables(String input) { if (input == null || !input.contains("${")) { return input; } // 正则匹配所有${xxx}格式的占位符 Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}"); Matcher matcher = pattern.matcher(input); StringBuilder sb = new StringBuilder(); while (matcher.find()) { String envVarName = matcher.group(1); String envVarValue = System.getenv(envVarName); // 若环境变量不存在,保留原占位符;可根据需求改为返回空或抛出异常 String replacement = envVarValue != null ? Matcher.quoteReplacement(envVarValue) : matcher.group(0); matcher.appendReplacement(sb, replacement); } matcher.appendTail(sb); return sb.toString(); } public String getString() { return props.getProperty(value); } public int getInt() throws NumberFormatException { String str = getString(); if (str == null || str.length() == 0) { return 0; } else { return Integer.parseInt(str); } } }
关键修改说明
- 新增解析方法:
resolveEnvironmentVariables方法通过正则匹配${ENV_VAR}格式的占位符,提取环境变量名后调用System.getenv()获取对应值,完成替换。如果环境变量不存在,默认保留原占位符(可根据业务需求调整,比如改为返回空字符串或抛出异常)。 - 初始化时解析:在
initEnvironment方法中,将从ResourceBundle读取到的原始属性值先经过解析处理,再存入Properties对象。这样所有属性在枚举类初始化阶段就完成了环境变量替换,后续调用getString时直接返回解析后的结果,完全不影响原有代码的调用逻辑。
这样修改后,properties文件中的${APPLICATION_CONF_PATH}会被替换为对应环境变量的值,拼接格式的${COMMON_SAVE_PATH}${APPLICATION_SAVE_PATH}也会被正确解析为两个环境变量值的组合,完美适配Kubernetes环境的配置需求。
内容的提问来源于stack exchange,提问作者Mirza Prangon
相关产品推荐
相关产品推荐

