Dynamic Configuration Refresh in Spring Cloud: From Config Data to RefreshScope
Baseline: Spring Boot 3.x, Spring Cloud 202x.x, Spring Cloud Alibaba, and Nacos 2.x. Versions must be used in combinations listed in the official compatibility matrix.
1. Startup Loading and Runtime Refresh
Modern Spring Boot projects favor Config Data imports:
spring:
application:
name: order-service
config:
import: optional:nacos:order-service.yaml
Config Data establishes the initial Environment before the application context is created; it is not the same as the legacy bootstrap.yml. Bootstrap can still be used for legacy projects or specific early-initialization scenarios, but should not be the default entry point for new projects.
2. The Real Semantics of RefreshScope
@RefreshScope uses a scoped proxy to cache the target object. A refresh destroys the target, and the next call recreates it; it does not instantly change the fields of arbitrary beans. Beans that hold connection pools, thread pools, remote clients, or local caches must explicitly close their old resources and create new ones.
3. Nacos Configuration
spring:
cloud:
nacos:
server-addr: <NACOS_SERVER_ADDR>
username: <NACOS_USERNAME>
password: <NACOS_PASSWORD>
config:
file-extension: yaml
refresh-enabled: true
For the exact property paths, refer to the current starter's configuration metadata. Do not commit usernames, passwords, or production addresses to Git.
4. Typical Refresh Flow
Nacos 发现变更 -> 客户端发布刷新事件 -> Spring 更新 Environment
-> ConfigurationProperties 重新绑定 -> RefreshScope 清理目标缓存
-> 下次调用创建新对象
5. Production Boundaries
Pin dependency and image versions; secure the Actuator refresh endpoint; establish auditing, approval, canary rollout, and rollback for configuration changes; monitor refresh failures and bean recreation failures.