top of page
Search

Dynamic application configuration in Spring Boot

  • Writer: Mark Kendall
    Mark Kendall
  • Dec 2, 2024
  • 3 min read

Dynamic application configuration in Spring Boot allows you to update configuration properties at runtime without restarting the application. This is particularly useful for applications that need to adapt to changing environments or user preferences. Here are some key techniques and tools for achieving dynamic configuration:

1. Using Spring Cloud Config

Spring Cloud Config provides server and client-side support for externalized configuration in a distributed system. It allows you to manage configuration properties in a central location and update them dynamically.

Setup

  1. Add Dependencies:

   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-config</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-actuator</artifactId>
   </dependency>
  1. Configure the Config Server: Create a Spring Boot application to act as the Config Server and configure it to read properties from a Git repository or a file system.

  2. Client Configuration: In your Spring Boot application, configure the application to use the Config Server by setting the spring.cloud.config.uri property in bootstrap.properties:

   spring.cloud.config.uri=http://localhost:8888
  1. Enable Refresh Scope: Use the @RefreshScope annotation on beans that need to be refreshed when configuration changes.

   @RefreshScope
   @RestController
   public class MyController {
       @Value("${my.property}")
       private String myProperty;

       @GetMapping("/property")
       public String getProperty() {
           return myProperty;
       }
   }
  1. Trigger Refresh: Use the /actuator/refresh endpoint to refresh the configuration properties dynamically.

   curl -X POST http://localhost:8080/actuator/refresh

2. Using Spring Cloud Bus

Spring Cloud Bus links nodes of a distributed system with a lightweight message broker. It can be used to broadcast configuration changes across multiple instances.

Setup

  1. Add Dependencies:

   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-bus-amqp</artifactId>
   </dependency>
  1. Configure Message Broker: Set up a message broker like RabbitMQ or Kafka.

  2. Broadcast Changes: When a configuration change is detected, Spring Cloud Bus will broadcast the change to all connected nodes, triggering a refresh.

3. Using @DynamicPropertySource

The @DynamicPropertySource annotation allows you to dynamically add properties to the Spring Environment during tests.

Example

@SpringBootTest
@Testcontainers
public class MyTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:11")
        .withDatabaseName("testdb")
        .withUsername("user")
        .withPassword("password");

    @DynamicPropertySource
    static void registerPgProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }

    @Autowired
    private DataSource dataSource;

    @Test
    void testDatabaseConnection() throws SQLException {
        try (Connection connection = dataSource.getConnection()) {
            assertNotNull(connection);
        }
    }
}

4. Using Environment and MutablePropertySources

You can programmatically update properties in the Spring Environment using ConfigurableEnvironment and MutablePropertySources.

Example

@Service
public class PropertyUpdaterService {

    @Autowired
    private ConfigurableEnvironment environment;

    public void updateProperty(String key, String value) {
        MutablePropertySources propertySources = environment.getPropertySources();
        Map<String, Object> dynamicProperties = new HashMap<>();
        dynamicProperties.put(key, value);
        propertySources.addFirst(new MapPropertySource("dynamicProperties", dynamicProperties));
    }
}

5. Using Azure App Configuration

Azure App Configuration provides a centralized place to manage application settings and feature flags. It supports dynamic configuration updates.

Setup

  1. Add Dependencies:

   <dependency>
       <groupId>com.microsoft.azure</groupId>
       <artifactId>azure-spring-cloud-appconfiguration-config</artifactId>
   </dependency>
  1. Configure Azure App Configuration: Set up your Spring Boot application to use Azure App Configuration by configuring the connection string and enabling dynamic refresh.

  2. Enable Refresh: Use the @RefreshScope annotation and trigger refreshes using the Azure App Configuration refresh mechanism.

By using these techniques, you can effectively manage and update your Spring Boot application's configuration dynamically, ensuring it adapts to changing requirements without downtime[1][2][3][4][5][6][7].

If you have any specific questions or need further details, feel free to ask!


References

 
 
 

Recent Posts

See All

Comments


Post: Blog2_Post

Subscribe Form

Thanks for submitting!

©2020 by LearnTeachMaster DevOps. Proudly created with Wix.com

bottom of page