MLS
MLS

Reputation: 637

Refresh springboot configuration dynamically

Is there any way to refresh springboot configuration as soon as we change .properties file?

I came across spring-cloud-config and many articles/blogs suggested to use this for a distributed environment. I have many deployments of my springboot application but they are not related or dependent on one another. I also looked at few solutions where they suggested providing rest endpoints to refresh configs manually without restarting application. But I want to refresh configuration dynamically whenever I change .properties file without manual intervention.

Any guide/suggestion is much appreciated.

Upvotes: 3

Views: 4318

Answers (2)

teknopaul
teknopaul

Reputation: 6770

Call this to reload @RefreshScope beans

ctx.getBean(RefreshScope.class).refreshAll();

Upvotes: 0

Dovmo
Dovmo

Reputation: 8749

Can you just use the Spring Cloud Config "Server" and have it signal to your Spring Cloud client that the properties file changed. See this example:

https://spring.io/guides/gs/centralized-configuration/

Under the covers, it is doing a poll of the underlying resource and then broadcasts it to your client:

    @Scheduled(fixedRateString = "${spring.cloud.config.server.monitor.fixedDelay:5000}")
    public void poll() {
        for (File file : filesFromEvents()) {
            this.endpoint.notifyByPath(new HttpHeaders(), Collections
                    .<String, Object>singletonMap("path", file.getAbsolutePath()));
        }
    }

If you don't want to use the config server, in your own code, you could use a similar scheduled annotation and monitor your properties file:

@Component
public class MyRefresher {

    @Autowired
    private ContextRefresher contextRefresher;

    @Scheduled(fixedDelay=5000)
    public void myRefresher() {
        // Code here could potentially look at the properties file 
        // to see if it changed, and conditionally call the next line...
        contextRefresher.refresh();
    } 
}

Upvotes: 4

Related Questions