0
0
SpringbootHow-ToBeginner · 4 min read

How to Use @Cacheable in Spring Boot for Easy Caching

In Spring Boot, use the @Cacheable annotation on a method to cache its result based on input parameters. This avoids repeated execution by returning cached data on subsequent calls with the same arguments.
📐

Syntax

The @Cacheable annotation is placed above a method to enable caching. You specify the cache name with value or cacheNames. When the method runs, Spring checks if the result for given parameters is cached; if yes, it returns the cached result instead of running the method again.

  • value / cacheNames: Name of the cache to use.
  • key: (Optional) Expression to define cache key, defaults to method parameters.
  • condition: (Optional) SpEL expression to cache only when true.
  • unless: (Optional) SpEL expression to skip caching when true.
java
@Cacheable(value = "cacheName", key = "#param")
public ReturnType methodName(ParameterType param) {
    // method logic
}
💻

Example

This example shows a Spring Boot service method that caches the result of a slow calculation. The first call caches the result, and subsequent calls with the same input return the cached value instantly.

java
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class CalculationService {

    @Cacheable("squareCache")
    public int square(int number) {
        try {
            Thread.sleep(3000); // Simulate slow calculation
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return number * number;
    }
}

// In your Spring Boot main class or config, enable caching:
// @EnableCaching

// Usage example:
// CalculationService service = context.getBean(CalculationService.class);
// System.out.println(service.square(4)); // Takes 3 seconds, returns 16
// System.out.println(service.square(4)); // Returns 16 instantly from cache
Output
First call output after ~3 seconds: 16 Second call output instantly: 16
⚠️

Common Pitfalls

  • For @Cacheable to work, caching must be enabled with @EnableCaching in a configuration class.
  • Methods must be called from outside the bean for caching to apply; self-calls inside the same class bypass caching.
  • Cache keys default to all method parameters; complex objects may need custom key expressions.
  • Using mutable objects as cache keys can cause unexpected behavior.
java
/* Wrong: calling cached method internally disables caching */
@Service
public class MyService {

    @Cacheable("dataCache")
    public String getData(String id) {
        return expensiveCall(id);
    }

    public String expensiveCall(String id) {
        // This call bypasses cache if called internally
        return getData(id);
    }
}

/* Right: call cached method from outside or restructure code */
📊

Quick Reference

PropertyDescriptionDefault
value / cacheNamesName of the cache to store resultsRequired
keySpEL expression for cache keyAll method parameters
conditionSpEL expression to cache only if trueAlways cache
unlessSpEL expression to skip caching if trueNever skip
syncIf true, cache loading is synchronizedfalse

Key Takeaways

Add @EnableCaching to your Spring Boot app to activate caching support.
Use @Cacheable on methods to cache their return values based on input parameters.
Cache keys default to method arguments but can be customized with SpEL expressions.
Avoid calling @Cacheable methods from within the same class to ensure caching works.
Choose meaningful cache names and configure cache managers for production use.