Exchange rates in Java and Spring Boot
Build a typed Spring Boot client for live FX rates with RestClient, BigDecimal, environment-based authentication, and explicit freshness fields.
Spring RestClient can map exchangerate.dev JSON directly into a Java record. Keep rates as BigDecimal, inject the API key from configuration, and retain source, market_session, and data_updated_at instead of reducing the response to one number.
RestClient for a synchronous typed client and let it reject 4xx and 5xx responses by default.BigDecimal; do not convert money through binary floating-point arithmetic.EXCHANGERATE_API_KEY, never from a committed properties file.data_updated_at with the rate so downstream jobs can enforce their own freshness rule.Create a typed RestClient
The response record below keeps the rate map and the fields needed to interpret it. Jackson maps the snake-case JSON names through @JsonProperty, while Spring handles the HTTP request and JSON decoding.
Load the key from the environment
Handle freshness and errors explicitly
RestClient.retrieve() throws on 4xx and 5xx responses by default, so a failed upstream call does not become a cached zero. Add bounded timeouts in the shared request factory, and retry only transient failures. A 401 needs a key fix; a sustained 429 needs less traffic or a higher limit.
BigDecimal, multiply with an explicit rounding policy, and round only for the target currency at the display boundary. The API rate should remain at full precision.- Reuse one configured RestClient across requests.
- Set connection and read timeouts on its request factory.
- Cache only successful responses.
- Persist source, marketSession, and dataUpdatedAt with the rate.