Search code examples
javaspringspring-bootspring-cloud

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.


Solution

  • 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
        }
    }