@RefreshScope 是 Spring Cloud Config 实现配置动态刷新的关键注解,它使被标记的 Bean 在调用时销毁旧实例并按新配置重建,从而获取最新值,需配合 /actuator/refresh 端点及正确基础配置使用。

@RefreshScope 是 Spring Cloud Config 中实现配置动态刷新的关键注解,但它本身不直接“监听”配置变化,而是配合 /actuator/refresh 端点和 Spring Cloud 的刷新机制协同工作。它的核心作用是:让被标记的 Bean 在配置刷新时被重新创建(即“懒加载+按需重建”),从而获取最新配置值。
为什么需要 @RefreshScope?
Spring 默认的单例 Bean 在启动后就初始化完成,其字段值(如 @Value("${xxx}") 注入的值)不会随远程配置变更而自动更新。@RefreshScope 将 Bean 标记为“可刷新作用域”,使其在下一次调用时,先销毁旧实例、再按新配置重新创建——相当于“延迟刷新”,避免了全局重启或手动重注入的复杂性。
使用前提与基础配置
- 项目必须引入
spring-cloud-starter-config和spring-boot-starter-actuator - 确保
management.endpoints.web.exposure.include=refresh(或设为*)已配置,否则无法访问/actuator/refresh - 配置中心(如 Git、Nacos、Consul)需正确连接,且应用能从 Config Server 拉取配置
- Bean 必须是 Spring 管理的组件(如
@Component、@Service、@Configuration),不能是 new 出来的对象
@RefreshScope 的典型用法
将注解加在类上,并配合 @Value 或 @ConfigurationProperties 使用:
@RefreshScope
@Component
public class SmsService {
@Value("${sms.timeout:5000}")
private long timeout;
public void send() {
System.out.println("Timeout: " + timeout); // 每次调用都走代理,读取最新值
}
}
注意:
– @RefreshScope 不能用于 @Bean 方法所在的 @Configuration 类(会导致刷新失败);
– 它对构造器注入无效(因为重建时仍走原构造逻辑),推荐使用 setter 或字段注入;
– 方法调用必须通过 Spring 代理(即不能在本类内部直接调用,否则绕过代理,拿不到新值)。
触发刷新的完整流程
- 修改配置中心中对应应用的配置(如 Git 仓库的
app-dev.yml) - 提交并推送变更
- 向应用发送 POST 请求:
curl -X POST http://localhost:8080/actuator/refresh - 响应返回 JSON 数组(如
["config.client.version", "sms.timeout"]),表示已刷新的配置项 - 下次调用
@RefreshScopeBean 的方法时,Spring 会先销毁旧实例、重建新实例,注入最新配置


















