Distributed Configuration
In a monolith,application.properties is fine. In microservices, changing a DB password in 50 services means 50 redeployments. We need Externalized Configuration.
1. Spring Cloud Config Server
This server connects to a Git repository (or filesystem) where your config files live, and serves them to microservices via an HTTP API. Setup Server:- Dependency:
spring-cloud-config-server. - Annotation:
@EnableConfigServer. application.yml:
user-service.ymlorder-service.ymlapplication.yml(Global config shared by all)
2. Config Client
The microservice that consumes the config.- Dependency:
spring-cloud-starter-config. - Bootstrap phase: The app needs to know where the Config Server is before it starts up fully.
src/main/resources/application.yml (Or bootstrap.yml in older versions):
user-service starts, it fetches configuration from the Config Server.
3. Profiles
You can haveuser-service-dev.yml and user-service-prod.yml in your git repo.
Run your app with:
java -jar app.jar --spring.profiles.active=prod
It will fetch the prod config automatically.
4. Dynamic Refresh (Hot Reload)
What if you change a property in Git and want to apply it without restarting the service?- Add
spring-boot-starter-actuatordependency. - Add
@RefreshScopeon the bean holding the config.
- Enable the refresh endpoint in
application.yml:
- Trigger the refresh:
POST http://localhost:8080/actuator/refresh
@RefreshScope.