@RefreshScope 是 Spring Cloud 提供的一个特殊作用域注解,用于让 Bean 在外部配置发生变化时能够动态刷新,而无需重启整个应用。它常用于结合 Spring Cloud Config 或 Nacos 等配置中心,实现配置的热更新。
✨ 核心作用
- 动态刷新配置:当配置中心的值发生变化时,标注了
@RefreshScope的 Bean 会被销毁并重新创建,新的 Bean 会自动绑定最新的配置。 - 避免重启服务:传统方式修改配置需要重启应用,而
@RefreshScope可以在运行时更新,保证服务不中断。 - 灵活性提升:适合微服务架构中频繁变动的配置(数据库连接、日志级别、外部 API 地址等)。
⚙️ 工作原理
- 作用域代理:Spring 为
@RefreshScopeBean 创建代理对象,拦截方法调用。 - 配置绑定:当触发刷新时(通常通过
/actuator/refresh端点),Spring 会重新绑定@Value或@ConfigurationProperties的值。 - Bean 生命周期管理:旧 Bean 被销毁,新 Bean重新实例化并注入最新配置
📌 使用场景
- 数据库连接信息动态更新:例如数据库 URL、用户名、密码在配置中心修改后,数据源 Bean 自动刷新。
- 日志级别调整:无需重启即可切换日志输出级别或目录。
- 外部 API 地址切换:当第三方服务地址变更时,应用可即时更新调用配置
🛠️ 使用步骤
- 引入依赖:
1 2 3 4 5 6 7 8<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> - 在 Bean 上添加注解:
1 2 3 4 5 6 7@Component @RefreshScope public class AppConfig { @Value("${app.message:Default message}") private String message; public String getMessage() { return message; } } - 触发刷新:
返回的 JSON 会列出被更新的配置项。
1curl -X POST http://localhost:8080/actuator/refresh
⚠️ 注意事项
- 必须启用 Actuator 的
/refresh端点,否则无法触发刷新。 - 只对标注了
@RefreshScope的 Bean 生效,普通 Bean 不会自动更新。 - Bean 会被重新创建,因此要注意其生命周期和可能的状态丢失问题。
👉 总结:@RefreshScope 是 Spring Cloud 中实现 配置热更新 的关键注解,适合在微服务架构中使用配置中心时,保证应用在不重启的情况下灵活适应配置变化。