java 48 lines · 7 steps

Refreshable feature settings in Spring

A Spring bean caches settings in memory and reloads them on refresh, serving typed reads without hitting the database each time.

Explained by highlit
1@RefreshScope
2@Component
3public class FeatureSettings {
4 
5 private final SettingsRepository repository;
6 
7 private final Map<String, String> cache = new ConcurrentHashMap<>();
8 
9 public FeatureSettings(SettingsRepository repository) {
10 this.repository = repository;
11 }
12 
13 @PostConstruct
14 void load() {
15 cache.clear();
16 repository.findAll().forEach(setting -> cache.put(setting.getKey(), setting.getValue()));
17 }
18 
19 public boolean isEnabled(String feature) {
20 return Boolean.parseBoolean(cache.getOrDefault(feature, "false"));
21 }
22 
23 public int getInt(String key, int defaultValue) {
24 String value = cache.get(key);
25 if (value == null) {
26 return defaultValue;
27 }
28 try {
29 return Integer.parseInt(value.trim());
30 } catch (NumberFormatException ex) {
31 return defaultValue;
32 }
33 }
34 
35 public Duration getDuration(String key, Duration defaultValue) {
36 return Optional.ofNullable(cache.get(key))
37 .map(Duration::parse)
38 .orElse(defaultValue);
39 }
40 
41 public String require(String key) {
42 String value = cache.get(key);
43 if (value == null) {
44 throw new IllegalStateException("Missing required setting: " + key);
45 }
46 return value;
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Loading data once into an in-memory map turns repeated config lookups into cheap reads.
  2. 2@RefreshScope lets a bean rebuild its state at runtime without restarting the application.
  3. 3Typed accessors with defaults keep parsing and null-handling out of every caller.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Refreshable feature settings in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code