Cobra1117
Cobra1117

Reputation: 1402

Detecting refreshing of RefreshScope beans

It is my understanding that when you use Spring Cloud's RefreshScope annotation, a Proxy to the data is injected, and the proxy is automatically updated if the backing information is changed. Unfortunately, I need to find a way to be alerted when that refresh occurs, so that my code can re-read the data from the refresh-scoped bean.

Simple example: A scheduled task whose schedule is stored in Cloud Config. Unless you wait until the next execution of the task (which could take a while) or regularly poll the configuration (which seems wasteful), there's no way to know if the configuration has changed.

Upvotes: 15

Views: 14976

Answers (4)

mOchi
mOchi

Reputation: 166

More specifically, after the refresh of properties and application context under scope RefreshScope, an event RefreshScopeRefreshedEvent is triggered. You can have a listener for this given the understanding that the properties has finished updates (you can be sure to capture updated values only).

Upvotes: 1

StasKolodyuk
StasKolodyuk

Reputation: 4524

EnvironmentChangeEvent is fired when there's a change in Environment. In terms of Spring Cloud Config it means it's triggered when /env actuator endpoint is called.

RefreshScopeRefreshedEvent is fired when refresh of @RefreshScope beans has been initiated, e.g. /refresh actuator endpoint is called.

That means that you need to register ApplicationListener<RefreshScopeRefreshedEvent> like that:

@Configuration
public class AppConfig {

    @EventListener(RefreshScopeRefreshedEvent.class)
    public void onRefresh(RefreshScopeRefreshedEvent event) {
        // Your code goes here...
    }

}

Upvotes: 22

Massimo Da Ros
Massimo Da Ros

Reputation: 403

I think an approach can be to annotate with @RefreshScope all your bean that have properties externalized by the configuration and annotated within @Value ( "${your.prop.key}" ) annotation.

These properties are updated when they changed on configuration.

Upvotes: 1

Ali Dehghani
Ali Dehghani

Reputation: 48133

When the refresh occurs EnvironmentChangeEvent would be raised in your config client, as the documentation states:

The application will listen for an EnvironmentChangedEvent and react to the change in a couple of standard ways (additional ApplicationListeners can be added as @Beans by the user in the normal way).

So, you can define your event listener for this event:

public class YourEventListener implements ApplicationListener<EnvironmentChangeEvent> {
    @Override
    public void onApplicationEvent(EnvironmentChangeEvent event) {
        // do stuff
    }
}

Upvotes: 16

Related Questions