在Spring Boot中实现关键配置的热加载(无需改业务代码)——实战与完整代码 - config"
1、背景与目标
很多系统最开始采用“启动时从远程配置中心拉取配置”的方式,但随着配置项动态变化、需要灰度/在线生效的场景越来越多,我们希望:
定时从远程配置中心拉取最新配置(你已有的配置拉取逻辑);
针对允许“实时更新”的配置项(由配置中心下发或管理界面控制),无需重启应用直接让 @Value("${...}") 注入的字段生效;
不改现有业务代码(不新增注解、不改@Value写法、不改 @ConfigurationProperties 使用方式);
对敏感或不可安全热更新的配置(数据库 URL、密码、host/port、token 等)要自动排除;
解决 .properties 文件中字符串转义导致的“字面不一致”误判问题(例如 http\://... vs http://...)。
下面是设计思路、关键点、以及可直接复制到项目中的完整代码。
2、总体设计
在现有项目里创建一个定时执行器实现定时拉取逻辑,仅在“配置对比并决定更新”处做两件事:
将要热刷新的 key 更新到 System.setProperty(key, value);
调用一个新增的刷新器去把新值写回已经实例化的 Bean 字段(@Value 注入的字段),达到热生效。
新增一个SpringValueRefresher,在Spring Bean初始化时扫描所有 @Value("${...}") 字段并缓存(key → list of FieldEntry)。
当触发刷新时(单 key 或批量),刷新器从 System.getProperty 或 Environment 中读取最新值并用反射修改字段值(做类型转换、避免重复赋值)。
扫描阶段和刷新阶段对 key 做双重排除:框架黑名单(spring.datasource.* 等) + 敏感关键字(url, uri, host, port, password, token 等),并支持从外部配置扩展白名单/黑名单。
在比较本地文件值与远端值时先 normalize(或用 Properties.load 风格解析)再比较,避免转义字符带来的误判。
3、安全原则与注意点
绝不对数据库连接、消息队列地址、认证 secret 等做盲目热更;必须排除或由人工极审后才允许;
热更新改变的是内存中 Bean 字段;若某个组件需要额外的重建(比如连接池),必须在配置变更后由业务代码监听事件并重建资源;
推荐使用白名单方式管理“哪个服务/页面允许自动更新”,并在 UI 层做禁用/隐藏。
全量刷新操作要谨慎(可人工触发或在 CI/CD 严格控制)。
4、核心类-增强版刷新器:SpringValueRefresher(带黑名单与敏感关键字)
在你的项目里增加以下核心类:SpringValueRefresher(类名自己随意)
如果你希望更明确控制哪些 key 可热更新(基于关键字,黑名单模式),可以使用下面这个封装好的类。它的行为:
启动时扫描所有 Bean 的 @Value 字段并缓存映射(key → FieldInfo list);
启动时跳过黑名单 key(例如 spring.datasource.*、spring.redis.* 等)和包含敏感关键字(url, uri, host, port, password, token 等)的 key;
在 refreshKey 时再次校验是否为被排除的 key(双保险);
支持基础类型转换。
你可以选择使用你原有 RefreshableValueProcessor(已实现),或者使用下面这个 SpringValueRefresher 作为替代/补充(两者功能类似,注意不要重复注册两个同时作用到同一字段)。
// 文件:com.xxx.configrefresh.core.SpringValueRefresher
package com.xxx.configrefresh.core;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@Slf4j
@Component
public class SpringValueRefresher implements ApplicationContextAware {
private final Map> keyFieldMap = new ConcurrentHashMap<>();
private ApplicationContext applicationContext;
private Environment environment;
/** 框架级黑名单(不允许热更新的配置前缀) */
private static final ListEXCLUDED_KEY_PATTERNS = Arrays.asList(
Pattern.compile("^spring\\.datasource\\..*"),
Pattern.compile("^spring\\.redis\\..*"),
Pattern.compile("^spring\\.rabbitmq\\..*"),
Pattern.compile("^spring\\.kafka\\..*"),
Pattern.compile("^spring\\.cloud\\..*"),
Pattern.compile("^feign\\..*"),
Pattern.compile("^server\\..*"),
Pattern.compile("^management\\..*"),
Pattern.compile("^logging\\..*")
);
/** 自定义敏感关键字(出现这些关键词的 key 一律不热更新) */
private static final ListEXCLUDED_KEYWORDS = Arrays.asList(
"url", "uri", "host", "port", "addr", "address", "password", "passwd", "secret", "token", "key"
);
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
this.environment = applicationContext.getEnvironment();
initCache();
}
/** 启动时扫描所有 Bean 的 @Value 注入字段 */
private void initCache() {
String[] beanNames = applicationContext.getBeanDefinitionNames();
for (String beanName : beanNames) {
Object bean;
try {
bean = applicationContext.getBean(beanName);
} catch (Exception e) {
continue; // 跳过未加载的 Bean
}
Class clazz = bean.getClass();
for (Field field : clazz.getDeclaredFields()) {
Value annotation = field.getAnnotation(Value.class);
if (annotation != null) {
String expr = annotation.value();
String key = parseKey(expr);
if (key == null) continue;
if (isExcludedKey(key)) {
log.debug("跳过不可热加载配置 key [{}]", key);
continue;
}
keyFieldMap.computeIfAbsent(key, k ->new ArrayList<>())
.add(new FieldInfo(bean, field, key));
log.info("监控配置 key [{}] ->{}.{}", key, clazz.getSimpleName(), field.getName());
}
}
}
log.info("SpringValueRefresher 初始化完成,共监控 {} 个配置 key", keyFieldMap.size());
}
/** 判断 key 是否在黑名单或包含敏感关键字 */
private boolean isExcludedKey(String key) {
// 1️⃣ 框架级前缀黑名单匹配
boolean matchPattern = EXCLUDED_KEY_PATTERNS.stream().anyMatch(p ->p.matcher(key).matches());
if (matchPattern) return true;
// 2️⃣ 包含敏感关键字的 key 一律排除
String lowerKey = key.toLowerCase(Locale.ROOT);
for (String kw : EXCLUDED_KEYWORDS) {
if (lowerKey.contains(kw)) return true;
}
return false;
}
/** 解析 @Value 表达式中的 key,如 ${app.name:default} ->app.name */
private String parseKey(String expr) {
if (expr.startsWith("${") && expr.endsWith("}")) {
expr = expr.substring(2, expr.length() - 1);
int idx = expr.indexOf(':');
return idx != -1 ? expr.substring(0, idx) : expr;
}
return null; 拼多多帮助力入口
}
/** 刷新单个 key 对应的 Bean 字段值 */
public void refreshKey(String key) {
if (isExcludedKey(key)) {
log.info("跳过不可热加载配置 [{}]", key);
return;
}
ListfieldInfos = keyFieldMap.get(key);
if (fieldInfos == null || fieldInfos.isEmpty()) {
log.debug("未找到使用 key [{}] 的 Bean 字段", key);
return;
}
String newValue = environment.getProperty(key);
for (FieldInfo info : fieldInfos) {
try {
info.field.setAccessible(true);
Object converted = convertType(newValue, info.field.getType());
info.field.set(info.bean, converted);
log.info("配置 [{}] 已刷新字段 {}.{} ->[{}]",
key, info.bean.getClass().getSimpleName(), info.field.getName(), newValue);
} catch (Exception e) {
log.error("刷新配置 key [{}] 时出错", key, e);
}
}
}
/** 简单类型转换 */
private Object convertType(String value, Class type) {
if (value == null) return null;
if (type == String.class) return value;
if (type == Integer.class || type == int.class) return Integer.valueOf(value);
if (type == Long.class || type == long.class) return Long.valueOf(value);
if (type == Boolean.class || type == boolean.class) return Boolean.valueOf(value);
if (type == Double.class || type == double.class) return Double.valueOf(value);
return value;
}
/** Bean + 字段封装 */
private static class FieldInfo {
final Object bean;
final Field field;
final String key;
FieldInfo(Object bean, Field field, String key) {
this.bean = bean;
this.field = field;
this.key = key;
}
}
}
5、创建定时器 ScmUpdateSchedule
此定时器代码仅供参考,不同系统有不同实现逻辑!!!
在拉取并决定“可自动更新”的 key 后,做写入 + 刷新
下面是 ScmUpdateSchedule 的关键片段(简化版),包含:调用远端 sendGetRequest()、判断版本;拉取允许自动更新的 key 列表 sendGetAutoUpdateCfgKeyRequest(...);解析远端 properties(使用你已有的 deserializePropertiesWithComments());normalize 值后比较,避免转义误判;对可自动更新的 key 执行 System.setProperty(key, newValue)(或 dynamicPropertySource.setProperty)并调用 springValueRefresher.refreshKey(key)。
注意:此处示例仅演示关键逻辑,保留你的 sendGetRequest / deserialize 方法不变。
// 文件:com.xxx.schedule.ScmUpdateSchedule(示例片段)
package com.xxx.schedule;
import com.xxx.configrefresh.core.SpringValueRefresher;
import com.xxx.configrefresh.core.DynamicPropertySource;
import com.nitc2.gantry.container.domain.ConfigurationResult;
import com.nitc2.gantry.util.LinkedProperties;
import com.nitc2.gantry.util.EtcPropertyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
@Slf4j
@Component
public class ScmUpdateSchedule {
@Autowired
private SpringValueRefresher springValueRefresher;
@Autowired(required = false)
private DynamicPropertySource dynamicPropertySource;
private ListneedAutoUpdateKeyList = List.of(); // 会在拉取后替换
@Scheduled(initialDelay = 10000, fixedRate = 600000)
public void upload() {
// 异步执行等你原有的线程池逻辑
scmDownload();
}
private void scmDownload() {
try {
Properties config = EtcPropertyUtils.properties("config.properties");
if (!Boolean.parseBoolean(config.getProperty("open.scm.config", "false"))) {
return;
}
String scmUrl = config.getProperty("scm.url");
Integer laneId = Integer.parseInt(config.getProperty("laneId", "0"));
String localVersion = "0";
Properties scmProps = EtcPropertyUtils.scmProperties();
if (scmProps != null) {
localVersion = scmProps.getProperty("scm.config.version", localVersion);
}
ConfigurationResult result = sendGetRequest(/*...*/);
if (result == null) return;
if (Boolean.TRUE.equals(result.getLatestClient())) {
log.info("配置已是最新,无需更新");
return;
}
// 拉取允许自动更新的 key 列表(你已有的方法)
sendGetAutoUpdateCfgKeyRequest(/*...*/);
// 假设 needAutoUpdateKeyList 被填充
LinkedProperties newProps = deserializePropertiesWithComments(result.getCfgMap().get("EtcTrade"));
// 遍历允许自动更新的 key,先 normalize 再比较
for (String key : needAutoUpdateKeyList) {
String newValRaw = newProps.getProperty(key);
String oldValRaw = EtcPropertyUtils.scmProperties().getProperty(key); // 或 existingProperties.getProperty(key)
String newVal = normalizePropertyValue(newValRaw);
String oldVal = normalizePropertyValue(oldValRaw);
if (!Objects.equals(newVal, oldVal)) {
log.info("热更新 key={} 新值={} 旧值={}", key, newVal, oldVal);
// 写入系统属性或 DynamicPropertySource
if (dynamicPropertySource != null) {
dynamicPropertySource.setProperty(key, newVal);
} else {
System.setProperty(key, newVal);
}
// 刷新注入的 @Value 字段
springValueRefresher.refreshKey(key);
// 同时写入本地文件 existingProperties.setProperty(key, newVal)
}
}
// 保存文件、处理版本号等(你的 updateConfigFile)
} catch (Exception e) {
log.error("处理在线配置异常", e);
}
}
private String normalizePropertyValue(String value) {
if (value == null) return null;
// 常见的 properties 转义反转(根据需要增减)
return value.replace("\\:", ":").replace("\\=", "=").replace("\\ ", " ").replace("\\\\", "\\");
}
// TODO: 你的 sendGetRequest / sendGetAutoUpdateCfgKeyRequest / deserializePropertiesWithComments 保持不变
}
6、补充说明与 FAQ
Q:为什么要用 System.setProperty?
A:它是最简单的方式,Environment 通常也会读取系统属性。
Q:是否支持 @ConfigurationProperties 绑定的类?
A:@ConfigurationProperties 的 Bean 绑定在初始化时把属性注入到 POJO 上,直接修改 Environment 不会自动重新绑定对应 Bean。对这类 Bean,你需要在操作后手动触发重新绑定或自己实现相似的反射更新逻辑(也可在 RefreshableValueProcessor 中扩展支持)。
Q:会影响性能吗?
A:扫描只在启动阶段一次完成;运行时只对有变化的 key 做反射赋值。正常情况下影响非常小。注意避免频繁全量刷新。
Q:如何记录变更审计?
A:建议在 ScmUpdateSchedule 的更新流程里记录:key、旧值、 新值、更新时间、来源(自动/人工)、操作人(若有)。
7、小结
我们通过在 Spring 容器启动时扫描 @Value 字段并缓存映射、在配置拉取后写入系统属性/动态 PropertySource,再通过反射把新值写回已有 Bean 字段,从而实现 无需改业务代码的热加载。
为了生产安全,我们添加了黑名单和敏感关键字过滤,并且在比较时做 normalize 来避免 properties 转义导致的误判。
我已在上文贴出完整的关键类代码(SpringValueRefresher、DynamicPropertySource、ScmUpdateSchedule 关键片段),可以直接拷贝进你的项目并根据项目包路径与工具方法(如 EtcPropertyUtils、deserializePropertiesWithComments)做小范围适配。