Skip to main content
skill CX Codex

spring-boot-cache — Claude Code skill: what it does, how to install

Configures caching in Spring Boot services using Caffeine, Redis, or Ehcache providers. Helps set up TTL policies, apply cache annotations, and trace cache misses.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-cache -a claude-code
Open on GitHub

What spring-boot-cache does

The skill provides reference patterns for Spring Boot cache abstraction. It guides the setup of Caffeine, Redis, or Ehcache providers alongside the required starter dependencies. Configuration starts with @EnableCaching on a config class, while service methods receive @Cacheable, @CachePut, or @CacheEvict.

It demonstrates how to shape cache keys with SpEL expressions and filter cached values using condition or unless guards. Verification relies on Spring Boot Actuator endpoints such as /actuator/caches and Micrometer metrics. Method self-invocation bypasses the Spring proxy. That breaks caching silently.

The guidance stresses keeping cache eviction aligned with database transactions. Mixing Spring annotations with JCache annotations on the same method causes conflicts and must be avoided. When pairing Caffeine with Redis in a multi-level cache, pub-sub invalidation channels are mandatory.

What it helps with

  • configure Caffeine, Redis, or Ehcache providers in Spring Boot
  • annotate service methods with @Cacheable, @CachePut, and @CacheEvict
  • define expiration TTL and eviction rules for stale entries
  • inspect cache hits and misses via Actuator metrics
  • resolve cache bypass issues caused by proxy self-invocation

Example prompts for the agent

  • Configure UserService caching with Caffeine and add an unless condition on null results
  • Set up Redis cache provider in Spring Boot with custom TTL and eviction via @CacheEvict
  • Diagnose why @Cacheable results in continuous cache misses during self-invocation

How to install spring-boot-cache

1Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-cache -a claude-code

2Manually: put the files in place

~/.claude/skills/spring-boot-cache/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/spring-boot-cache/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about spring-boot-cache

How do I install spring-boot-cache in Claude Code?

Run npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-cache -a claude-code in your terminal. This registers the skill for your Claude Code sessions.

Which cache providers does the skill cover?

The skill provides patterns for Caffeine, Redis, and Ehcache. It covers dependency setup and TTL configuration for each provider.

Why does a @Cacheable method fail to cache return values?

Spring caching uses proxies, so calling an annotated method from within the same class bypasses the interceptor. Make sure the method is public and @EnableCaching is present on a configuration class.

Source text

SKILL.md · MIT
---
name: spring-boot-cache
description: "Provides patterns for implementing Spring Boot caching: configures Redis/Caffeine/EhCache providers with TTL and eviction policies, applies @Cacheable/@CacheEvict/@CachePut annotations, validates cache hit/miss behavior, and exposes metrics via Actuator. Use when adding caching to Spring Boot services, configuring cache expiration, evicting stale data, or diagnosing cache misses."
allowed-tools: Read, Write, Bash
---

# Spring Boot Cache Abstraction

## Overview

6-step workflow for enabling cache abstraction, configuring providers (Caffeine,
Redis, Ehcache), annotating service methods, and validating behavior in
Spring Boot 3.5+ applications. Apply `@Cacheable` for reads, `@CachePut` for
writes, `@CacheEvict` for deletions. Configure TTL/eviction policies and expose
metrics via Actuator.

## When to Use

- Add `@Cacheable`, `@CachePut`, or `@CacheEvict` to service methods.
- Configure Caffeine, Redis, or Ehcache with TTL and capacity policies.
- Implement eviction strategies for stale data.
- Diagnose cache misses or invalidation issues.
- Expose hit/miss metrics via Actuator or Micrometer.

## Instructions

1. **Add dependencies** — `spring-boot-starter-cache` plus a provider:
   - Caffeine: `caffeine` starter
   - Redis: `spring-boot-starter-data-redis`
   - Ehcache: `ehcache` starter

2. **Enable caching** — annotate a `@Configuration` class with `@EnableCaching`
   and define a `CacheManager` bean.

3. **Annotate methods** — `@Cacheable` for reads, `@CachePut` for writes,
   `@CacheEvict` for deletions.

4. **Configure TTL/eviction** — set `spring.cache.caffeine.spec`,
   `spring.cache.redis.time-to-live`, or `spring.cache.ehcache.config`.

5. **Shape keys** — use SpEL in `key` attributes; guard with
   `condition`/`unless` for selective caching.

6. **Validate setup** — run integration test to confirm cache hit on second
   call; check `GET /actuator/caches` to verify cache manager registration;
   query `GET /actuator/metrics/cache.gets` for hit/miss ratios.

## Examples

### Example 1: Basic `@Cacheable` Usage

```java
@Service
@CacheConfig(cacheNames = "users")
class UserService {

    @Cacheable(key = "#id", unless = "#result == null")
    User findUser(Long id) { ... }
}
```

```
First call → cache miss, repository invoked
Second call → cache hit, repository skipped
```

### Example 2: Conditional Caching with SpEL

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

// Only expensive products are cached
```

### Example 3: Cache Eviction

```java
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) { ... }
```

For progressive scenarios (basic product cache, multilevel eviction, Redis
integration), load [`references/cache-examples.md`](references/cache-examples.md).

## Advanced Options

- Use JCache annotations (`@CacheResult`, `@CacheRemove`) for providers favoring
  JSR-107 interoperability; avoid mixing with Spring annotations on the same method.
- Cache reactive return types (`Mono`, `Flux`) or `CompletableFuture` values.
- Apply HTTP `CacheControl` headers when exposing cached responses via REST.
- Schedule periodic eviction with `@Scheduled` for time-bound caches.
- Create a `CacheManagementService` for programmatic `cacheManager.getCache(name)`.

## Troubleshooting

If cache misses persist after adding `@Cacheable`:

1. Verify `@EnableCaching` is present on a `@Configuration` class.
2. Confirm the method is public and called from outside the class (Spring uses
   proxies; self-invocation bypasses the cache).
3. Validate SpEL key expressions resolve correctly.
4. Confirm the cache manager bean is registered as `cacheManager` or explicitly
   referenced via `cacheManager = "myCacheManager"`.

## References

- [`references/spring-framework-cache-docs.md`](references/spring-framework-cache-docs.md):
  curated excerpts from Spring Framework Reference Guide.
- [`references/spring-cache-doc-snippet.md`](references/spring-cache-doc-snippet.md):
  narrative overview from Spring documentation.
- [`references/cache-core-reference.md`](references/cache-core-reference.md):
  annotation parameters, dependency matrices, property catalogs.
- [`references/cache-examples.md`](references/cache-examples.md):
  end-to-end examples with tests.

## 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; push metrics via Micrometer.
- Tune TTLs based on data staleness tolerance; document rationale in code.
- Guard caches storing 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.
- Validate serialization compatibility when caching across service instances.
- Monitor memory footprint to prevent OOM with in-memory stores.
- Caffeine + Redis multi-level caches require publish/subscribe invalidation channels.

## Related Skills

- [`../spring-boot-rest-api-standards`](../spring-boot-rest-api-standards/SKILL.md)
- [`../spring-boot-test-patterns`](../spring-boot-test-patterns/SKILL.md)
- [`../unit-test-caching`](../unit-test-caching/SKILL.md)

© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar skills

All skills for Backend and APIs →

From the same set96

nestjs-code-review A skill that reviews NestJS apps: controllers, services, modules, DI, guards and database patterns. Useful before merging a pull request. CX Codex +1 3,800installs spring-boot-resilience4j Generates Resilience4j fault tolerance patterns for Spring Boot 3.x projects. Use it to configure circuit breakers and retry logic. CX Codex +1 3,800installs unit-test-service-layer A skill that gives the agent a Mockito pattern for service-layer unit tests: mock repositories, verify calls, cover exception paths. CX Codex +1 3,800installs nestjs-best-practices A skill that hands your agent a rulebook for NestJS: module boundaries, provider scopes, exception filters, DTO validation and Drizzle ORM. CX Codex +1 3,800installs zod-validation-utilities Guides Zod v4 validation for TypeScript APIs, forms, and configuration. Use it when external input needs parsing, coercion, and clear validation errors. CX Codex +1 3,800installs spring-boot-event-driven-patterns A Spring Boot 3.x skill for domain events, @TransactionalEventListener, Kafka messaging and the transactional outbox pattern. Useful when sync calls between services need to become events. CX Codex +1 3,800installs chunking-strategy Configures document chunking workflows and overlap for RAG pipelines and vector search. It validates semantic coherence and tunes retrieval precision. CX Codex +1 3,800installs aws-sdk-java-v2-rds Guides AI agents in managing Amazon RDS databases via the AWS SDK for Java 2.x. Useful for provisioning instances, snapshots, and parameter groups. CX Codex +1 3,700installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor