How to refresh/reload application properties runtime in spring boot ?

vishalpaalakurthi - Sep 24 '20 - - Dev Community

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>
Enter fullscreen mode Exit fullscreen mode
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

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/
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

from now, we can get new value from the next access.

Thank you for reading my blog. 🤩

. . . . . . . . . . .
Terabox Video Player