Dynamic Refresh of Spring Boot Configuration from Database Without Restart
This article demonstrates how to dynamically load Spring Boot configuration from a database and refresh specific beans at runtime using Spring Cloud's ContextRefresher, enabling configuration changes without restarting the application.
In many projects there is a need to modify Spring Boot configuration at runtime without restarting the application.
This article explains how to load configuration from a database and provide a one‑click refresh mechanism.
The approach consists of several key steps:
Obtain the application context via ConfigurableApplicationContext.
Get the current Environment object.
Fetch the latest configuration from the database (or other source).
Replace the current environment properties using MutablePropertySources and a new MapPropertySource.
Refresh specific beans by invoking ContextRefresher.refresh(), optionally asynchronously.
The article provides Maven dependencies for Spring Cloud 2021.0.1, shows how to add @RefreshScope to beans, and gives concrete code examples for acquiring the context, environment, loading configuration via gRPC, updating the property source, and triggering an asynchronous refresh.
<!-- Maven parent dependency -->
<spring-cloud.version>2021.0.1</spring-cloud.version>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> @RefreshScope
public class ConfigService {
@Value("${grpc.client.xyregiserve.port}")
private String regiservePort;
@Value("${grpc.client.xyregiserve.url}")
private String regiserveUrl;
@Autowired
private ConfigurableApplicationContext applicationContext;
@Autowired
private ContextRefresher contextRefresher;
// ... method refreshConfig() implements the steps described above ...
}A REST controller with endpoint /refresh/config is presented to trigger the refresh:
@RestController
@RequestMapping("/refresh/config")
public class RefreshConfig {
@Autowired
private ConfigService configService;
@GetMapping
public AjaxResult refresh() throws Exception {
configService.refreshConfig();
return AjaxResult.success();
}
}Finally, a test class demonstrates that after changing a configuration value in the database, calling the refresh endpoint updates the in‑memory configuration without restarting the service.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
