SpringBoot + @RefreshScope:动态刷新配置的终极指南
SpringBoot + @RefreshScope:动态刷新配置的终极指南
@RefreshScope的神奇力量,让你的应用配置在运行时动态刷新,彻底告别服务重启的烦恼。

@RefreshScope完美解决了这些问题,实现配置热更新,让应用像乐高积木一样灵活重组!

-
工作原理图解
graph TD
A[修改配置文件] --> B[发送POST刷新请求]
B --> C[/actuator/refresh 端点]
C --> D[RefreshScope 刷新机制]
D --> E[销毁旧Bean并创建新Bean]
E --> F[新配置立即生效]
-
关键技术解析
-
配置绑定:当配置更新时,重新绑定 @Value注解的值 -
Bean生命周期管理:销毁并重新初始化被 @RefreshScope标记的Bean


<!-- pom.xml -->
<dependencies>
<!-- Spring Boot基础依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 配置刷新核心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 配置中心支持 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
<version>3.1.3</version>
</dependency>
</dependencies>
// 主应用类
@SpringBootApplication
@EnableRefreshScope // 关键注解:开启配置刷新能力
publicclassDynamicConfigApp {
publicstaticvoidmain(String[] args) {
SpringApplication.run(DynamicConfigApp.class, args);
}
}
# 应用基础配置
app:
feature:
enabled:true
timeout:5000
retry-count:3
welcome-msg:"Hello, Dynamic Config!"
# 暴露刷新端点(关键!)
management:
endpoints:
web:
exposure:
include:refresh,health,info
@Service
@RefreshScope// 标记此Bean支持动态刷新
publicclassFeatureService {
// 注入可刷新的配置项
@Value("${app.feature.enabled}")
privateboolean featureEnabled;
@Value("${app.feature.timeout}")
privateint timeout;
@Value("${app.feature.retry-count}")
privateint retryCount;
@Value("${app.feature.welcome-msg}")
private String welcomeMessage;
public String getFeatureConfig() {
return String.format("""
Feature Enabled: %s
Timeout: %d ms
Retry Count: %d
Message: %s
""", featureEnabled, timeout, retryCount, welcomeMessage);
}
}
@RestController
@RequestMapping("/config")
publicclassConfigController {
privatefinal FeatureService featureService;
// 构造函数注入
publicConfigController(FeatureService featureService) {
this.featureService = featureService;
}
@GetMapping
public String getConfig() {
return featureService.getFeatureConfig();
}
}
curl -X POST http://localhost:8080/actuator/refresh
["app.feature.timeout", "app.feature.welcome-msg"]


-
作用域代理原理
// 伪代码:Spring如何实现动态刷新
publicclassRefreshScopeProxyimplementsApplicationContextAware {
private Object targetBean;
@Override
public Object invoke(Method method) {
if (configChanged) {
// 1. 销毁旧Bean
context.destroyBean(targetBean);
// 2. 重新创建Bean
targetBean = context.getBean(beanName);
}
return method.invoke(targetBean, args);
}
}
-
刷新范围控制技巧
@Component
@RefreshScope
publicclassPaymentService {
// 只有带@Value的属性会刷新
@Value("${payment.timeout}")
privateint timeout;
// 不会被刷新的属性
privatefinalStringapiVersion="v1.0";
}
@Configuration
@RefreshScope// 整个配置类可刷新
publicclassAppConfig {
@Bean
@RefreshScope
public FeatureService featureService() {
returnnewFeatureService();
}
@Value("${app.theme}")
private String theme;
}


-
安全加固配置
management:
endpoint:
refresh:
enabled:true
endpoints:
web:
exposure:
include:refresh
base-path:/internal# 修改默认路径
path-mapping:
refresh:secure-refresh# 端点重命名
# 添加安全认证
spring:
security:
user:
name:admin
password:$2a$10$NVM0n8ElaRgg7zWO1CxUdei7vWoQP91oGycgVNCY8GQEx.TGx.AaC
-
自动刷新方案
//bootstrap.yml
spring:
cloud:
nacos:
config:
server-addr:localhost:8848
auto-refresh:true # 开启自动刷新

-
• 检查是否添加 @RefreshScope -
• 确认刷新端点返回了修改的配置项 -
• 查看日志: logging.level.org.springframework.cloud=DEBUG
# 使用Spring Cloud Bus同步刷新
curl-XPOSThttp://host:port/actuator/bus-refresh
@PreDestroy
publicvoidcleanUp() {
// 清理资源
}

# 修改后立即生效
feature.new-checkout.enabled=true
@RefreshScope
publicclassLogConfig {
@Value("${logging.level.root}")
private String logLevel;
// 动态应用新日志级别
}
# 动态修改连接池配置
spring.datasource.hikari.maximum-pool-size=20

@RefreshScope,我们实现了:
摘抄自网络,便于检索查找。

浙公网安备 33010602011771号