How to refresh/reload application properties runtime in spring boot ?
vishalpaalakurthi
Posted on September 24, 2020
In this tutorial, we are going to learn how to reload application properties in spring boot.
We have many options in spring boot, now I am explaining the easiest one here.
Refresh beans with @ConfigurationProperties
For Reloading properties, spring cloud has introduced @RefreshScope annotation which can be used for refreshing beans.
Spring Actuator provides different endpoints for health, metrics. but spring cloud will add extra end point /refresh to reload all the properties.
Required maven/gradle dependencies
- Spring actuator
- Spring cloud starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
Then, add below property to application properties file
management.endpoints.web.exposure.include=refresh
// Db Properties, Values to be store in a Map
db.dbProps.awsEndPoint=localhost:8080/aws/
db.dbProps.azureEndPoint=localhost:8080/azure/
Now, Create a class for configuring properties and add @RefreshScope annotation to class.
@Component
@ConfigurationProperties(prefix = "db")
@RefreshScope
public class DbProperties {
// This is for storing application properties in a Map
public Map<String, String> dbProps;
public Map<String, String> getDbProps() {
return dbProps;
}
public void setDbProps(Map<String, String> dbProps) {
this.dbProps = dbProps;
}
// Get property value using key
public String getDbPropData(String key) {
return dbProps.get(key);
}
}
Above code create a scope for refreshing application properties data.
Now, when you change data in application properties. we need to give a POST REST call using below URL.
http://localhost:8080/actuator/refresh
from now, we can get new value from the next access.
Thank you for reading my blog. 🤩
Posted on September 24, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.