Video in progress
How does @RefreshScope work, and what are the limitations of updating a setting without restarting the application?
@RefreshScope (Spring Cloud) wraps the bean in a proxy. When /actuator/refresh is called, the Environment is re-read, such beans are discarded, and they're recreated with the new value on the next call. It works per instance and doesn't suit every bean.
📖 Answer
@Service
@RefreshScope
class DiscountPolicy {
private final BigDecimal rate;
DiscountPolicy(@Value("${shop.discount-rate}") BigDecimal rate) {
this.rate = rate;
}
}
The sequence:
- A value changed in the Config Server (or a Kubernetes ConfigMap).
POST /actuator/refreshis called: Spring Cloud loads the newEnvironmentand returns the list of changed keys.- The
@RefreshScopebeans are discarded. Whoever injected them is really holding a proxy, so on the next method call the bean is recreated with the new value. @ConfigurationPropertiesbeans are rebound throughEnvironmentChangeEventeven without@RefreshScope.
The limitations:
- it's per instance: with 10 pods you'd have to call refresh 10 times. Spring Cloud Bus (through Kafka/RabbitMQ) or Kubernetes integration automates this;
- stateful beans: refreshing a
DataSource, connection pool or thread pool drops connections or leaves a half-applied state. For such settings a restart is safer; @Valuein an ordinary singleton isn't updated, because the value was read once at creation;- brief inconsistency: during a refresh some pods work with the old value and some with the new;
- leaving the
/actuator/refreshendpoint open is a security hole, so protect it.
In practice: refresh is convenient for simple, frequently changing values like feature flags and limits. For an infrastructure setting, a rolling restart is simpler and more reliable.
Sign up to mark studied questions and save your progress.