Spring Boot Cache Abstraction

VerifiedSafe

Provides patterns for enabling and operating the Spring Cache abstraction in Spring Boot. Use for implementing application-level caching to improve performance.

Sby Skills Guide Bot
DevelopmentIntermediate
7/22/2026
Claude CodeCursorWindsurfCodex
#spring-boot#caching#java#spring-cache#performance

Recommended for

Automated summary

This skill provides a workflow for enabling and operating the Spring Boot cache abstraction: annotations, cache managers (Caffeine, Redis, JCache), eviction strategies and monitoring.

Strengths

  • Seven-step walkthrough covering dependencies, @EnableCaching, configuration, annotations, SpEL keys, eviction and monitoring.
  • Concrete Maven and Gradle snippets for the cache starter and Caffeine, including a CaffeineCacheManager bean.
  • Shows how to swap cache providers without changing business code.
  • Highlights common pitfalls: SpEL keys, condition/unless clauses, scheduled invalidation.

Limitations

  • Redis and Ehcache configuration is only mentioned at the starter level, with no detailed example.
  • Assumes Java 17+ and Spring Boot 3.5.x; no guidance for older versions.
  • Provides no complete automated test to verify cache behavior.
When to use it

Use it when adding, configuring or debugging application-level caching in a Spring Boot service.

When not to use it

Avoid it for HTTP/CDN caching, advanced distributed cache concerns (consistency, sharding) or non-Spring Boot projects.

Security analysis

Safe
Quality score85/100

The skill provides declarative configuration and code patterns for Spring caching. It declares Read/Write/Bash but contains no destructive, exfiltration, or obfuscation instructions; Bash is only implied for normal build/test activities.

No concerns found

How this analysis is made

Examples

Annotate a service with caching
Add Spring Cache to my OrderService: annotate findOrder with @Cacheable, refreshOrder with @CachePut and cancelOrder with @CacheEvict, using the order id as the cache key and skipping null results.
Configure a Caffeine cache manager
Configure a CaffeineCacheManager in my Spring Boot 3.5 app with caches named users and orders, a 10-minute TTL and a 500-entry maximum size, in application.yml.
Debug a failing cache eviction
My @CacheEvict on updateUser isn't clearing the users cache — review my SpEL key expressions and beforeInvocation setting and tell me what's wrong.

name: spring-boot-cache description: Provides patterns for enabling and operating the Spring Cache abstraction in Spring Boot. Use when implementing application-level caching for performance-sensitive workloads. allowed-tools: Read, Write, Bash

Spring Boot Cache Abstraction

Overview

Spring Boot ships with a cache abstraction that wraps expensive service calls behind annotation-driven caches. This abstraction supports multiple cache providers (ConcurrentMap, Caffeine, Redis, Ehcache, JCache) without changing business code. The skill provides a concise workflow for enabling caching, managing cache lifecycles, and validating behavior in Spring Boot 3.5+ services.

When to Use

  • Add @Cacheable, @CachePut, or @CacheEvict to Spring Boot service methods.
  • Configure Caffeine, Redis, or JCache cache managers for Spring Boot.
  • Diagnose cache invalidation, eviction scheduling, or cache key issues.
  • Expose cache management endpoints or scheduled eviction routines.

Use trigger phrases such as "implement service caching", "configure CaffeineCacheManager", "evict caches on update", or "test Spring cache behavior" to load this skill.

Instructions

Follow these steps to implement caching in Spring Boot applications:

1. Add Cache Dependencies

Include spring-boot-starter-cache and your preferred cache provider (Caffeine, Redis, Ehcache) in the project dependencies.

2. Enable Caching

Add @EnableCaching to a @Configuration class and declare CacheManager bean(s) for your cache providers.

3. Define Cache Configuration

Configure cache names, TTL settings, and capacity limits in application.yml or via CacheManager customizer beans.

4. Anotate Service Methods

Apply @Cacheable for read operations, @CachePut for updates, and @CacheEvict for invalidation. Use @CacheConfig to define default cache names at class level.

5. Configure Cache Keys and Conditions

Use SpEL expressions to define cache keys (key = "#user.id"), conditions (condition = "#price > 0"), and unless clauses (unless = "#result == null").

6. Implement Cache Eviction Strategy

Create scheduled jobs or use @CacheEvict with allEntries=true to periodically clear time-sensitive caches.

7. Monitor Cache Performance

Enable Actuator cache endpoint to observe hit/miss ratios. Consider Micrometer metrics for production observability.

Prerequisites

  • Java 17+ project based on Spring Boot 3.5.x (records encouraged for DTOs).
  • Dependency spring-boot-starter-cache; add provider-specific starters as needed (spring-boot-starter-data-redis, caffeine, ehcache, etc.).
  • Constructor-injected services that expose deterministic method signatures.
  • Observability stack (Actuator, Micrometer) when operating caches in production.

Quick Start

  1. Add dependencies

    <!-- Maven -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency> <!-- Optional: Caffeine -->
        <groupId>com.github.ben-manes.caffeine</groupId>
        <artifactId>caffeine</artifactId>
    </dependency>
    
    implementation "org.springframework.boot:spring-boot-starter-cache"
    implementation "com.github.ben-manes.caffeine:caffeine"
    
  2. Enable caching

    @Configuration
    @EnableCaching
    class CacheConfig {
        @Bean
        CacheManager cacheManager() {
            return new CaffeineCacheManager("users", "orders");
        }
    }
    
  3. Annotate service methods

    @Service
    @CacheConfig(cacheNames = "users")
    class UserService {
    
        @Cacheable(key = "#id", unless = "#result == null")
        User findUser(Long id) { ... }
    
        @CachePut(key = "#user.id")
        User refreshUser(User user) { ... }
    
        @CacheEvict(key = "#id", beforeInvocation = false)
        void deleteUser(Long id) { ... }
    }
    
  4. Verify behavior

    • Run focused unit tests that call cached methods twice and assert repository invocations.
    • Inspect Actuator cache endpoint (if enabled) for hit/miss counters.

Implementation Workflow

1. Define Cache Strategy

  • Map hot-path read operations to @Cacheable.
  • Use @CachePut on write paths that must refresh cache entries.
  • Apply @CacheEvict (allEntries = true when invalidating derived caches).
  • Combine operations with @Caching to keep multi-cache updates consistent.

2. Shape Cache Keys and Conditions

  • Generate deterministic keys via SpEL (e.g. key = "#user.id").
  • Guard caching with condition = "#price > 0" for selective caching.
  • Prevent null or stale values with unless = "#result == null".
  • Synchronize concurrent updates via sync = true when needed.

3. Manage Providers and TTLs

  • Configure provider-specific options:
    • Caffeine spec: spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m
    • Redis TTL: spring.cache.redis.time-to-live=600000
    • Ehcache XML: define ttl and heap/off-heap resources.
  • Expose cache names via spring.cache.cache-names=users,orders,catalog.
  • Avoid on-demand cache name creation in production unless metrics cover usage.

4. Operate and Observe Caches

  • Surface cache maintenance via a dedicated CacheManagementService with programmatic cacheManager.getCache(name) access.
  • Schedule periodic eviction for time-bound caches using @Scheduled.
  • Wire Actuator cache endpoint and Micrometer meters to track hit ratio, eviction count, and size.

5. Test and Validate

  • Prefer slice or unit tests with Mockito/SpyBean to ensure method invocation counts.
  • Add integration tests with Testcontainers for Redis/Ehcache when using external providers.
  • Validate concurrency behavior under load (e.g. sync = true scenarios).

Advanced Options

  • Integrate JCache annotations when interoperating with providers that favor JSR-107 (@CacheResult, @CacheRemove). Avoid mixing with Spring annotations on the same method.
  • Cache reactive return types (Mono, Flux) or CompletableFuture values. Spring stores resolved values and resubscribes on hits; consider TTL alignment with publisher semantics.
  • Apply HTTP caching headers using CacheControl when exposing cached responses via REST.

Examples

Example 1: Basic @Cacheable Usage

Input:

// First call - cache miss, method executes
User user1 = userService.findUser(1L);

// Second call - cache hit, method skipped
User user2 = userService.findUser(1L);

Output:

// First call logs:
Hibernate: select u1_0.id,u1_0.name from users u1_0 where u1_0.id=?

// Second call: No SQL executed (served from cache)

Example 2: Conditional Caching with SpEL

Input:

@Cacheable(value = "products", key = "#id", condition = "#price > 100")
public Product getProduct(Long id, BigDecimal price) {
    return productRepository.findById(id);
}

// Only expensive products are cached
getProduct(1L, new BigDecimal("50.00"));   // Not cached
getProduct(2L, new BigDecimal("150.00"));  // Cached

Output:

Cache 'products' contents after operations:
{2=Product(id=2, price=150.00)}

Example 3: Cache Eviction

Input:

@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
    userRepository.deleteById(id);
}

deleteUser(1L);

Output:

Cache 'users' entry for key '1' removed

References

Best Practices

  • Prefer constructor injection and immutable DTOs for cache entries.
  • Separate cache names per aggregate (users, orders) to simplify eviction.
  • Log cache hits/misses only at debug to avoid noise; push metrics via Micrometer.
  • Tune TTLs based on data staleness tolerance; document rationale in code.
  • Guard caches that store PII or credentials with encryption or avoid caching.
  • Align cache eviction with transactional boundaries to prevent dirty reads.

Constraints and Warnings

  • Avoid caching mutable entities that depend on open persistence contexts.
  • Do not mix Spring cache annotations with JCache annotations on the same method.
  • Ensure multi-level caches (e.g. Caffeine + Redis) maintain consistency; prefer publish/subscribe invalidation channels.
  • Validate serialization compatibility when caching across service instances.
  • Monitor memory footprint to prevent OOM when using in-memory stores.

Related Skills

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/spring-boot-cache-abstraction-mrwakcam' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/spring-boot-cache-abstraction-mrwakcam/download' --output '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md.part' && mv '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md.part' '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Tools declared by the author (check availability in your agent): Read, Write, Bash

Original excerpt: Prerequisites
  • Java 17+ project based on Spring Boot 3.5.x (records encouraged for DTOs).
  • Dependency spring-boot-starter-cache; add provider-specific starters as needed (spring-boot-starter-data-redis, caffeine, ehcache, etc.).
  • Constructor-injected services that expose deterministic method signatures.
  • Observability stack (Actuator, Micrometer) when operating caches in production.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && test -s '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/spring-boot-cache' && cp -R '.skill-downloads/spring-boot-cache-abstraction-mrwakcam' '.claude/skills/spring-boot-cache'

Cursor
test -f '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && test -s '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/spring-boot-cache' && cp -R '.skill-downloads/spring-boot-cache-abstraction-mrwakcam' '.cursor/skills/spring-boot-cache'

Codex
test -f '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && test -s '.skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/spring-boot-cache' && cp -R '.skill-downloads/spring-boot-cache-abstraction-mrwakcam' '.agents/skills/spring-boot-cache'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/spring-boot-cache-abstraction-mrwakcam'

openskills read 'spring-boot-cache-abstraction-mrwakcam'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/spring-boot-cache-abstraction-mrwakcam/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills