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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Loading data once into an in-memory map turns repeated config lookups into cheap reads.
- 2@RefreshScope lets a bean rebuild its state at runtime without restarting the application.
- 3Typed accessors with defaults keep parsing and null-handling out of every caller.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/refreshable-feature-settings-in-spring-explained-java-4eb6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.