java 38 lines · 7 steps

Warming a Spring cache at startup

A Spring bean pre-loads a cache once all singletons are ready, so the first real request doesn't pay the cold-start cost.

Explained by highlit
1@Component
2public class RegionCacheWarmer implements SmartInitializingSingleton {
3 
4 private static final Logger log = LoggerFactory.getLogger(RegionCacheWarmer.class);
5 
6 private final RegionService regionService;
7 private final CacheManager cacheManager;
8 
9 public RegionCacheWarmer(RegionService regionService, CacheManager cacheManager) {
10 this.regionService = regionService;
11 this.cacheManager = cacheManager;
12 }
13 
14 @Override
15 public void afterSingletonsInstantiated() {
16 Cache cache = cacheManager.getCache("regions");
17 if (cache == null) {
18 log.warn("Cache 'regions' is not configured; skipping warm-up");
19 return;
20 }
21 
22 StopWatch watch = new StopWatch();
23 watch.start();
24 
25 List<String> codes = regionService.findActiveRegionCodes();
26 for (String code : codes) {
27 try {
28 regionService.getRegionByCode(code);
29 } catch (Exception ex) {
30 log.error("Failed to warm cache entry for region '{}'", code, ex);
31 }
32 }
33 
34 watch.stop();
35 log.info("Warmed 'regions' cache with {} entries in {} ms",
36 codes.size(), watch.getTotalTimeMillis());
37 }
38}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1SmartInitializingSingleton runs code after the whole context is built, making it ideal for cross-bean startup tasks.
  2. 2Guarding against a missing cache lets warm-up degrade gracefully instead of crashing the application.
  3. 3Isolating each entry's fetch in a try/catch keeps one bad record from aborting the entire warm-up.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

Warming a Spring cache at startup — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code