Video in progress

Strong Junior ⚡ Redis and caching

Caching isn't working in this code. What's the cause?

@Service
public class PriceService {

    @Cacheable("prices")
    public BigDecimal findById(long id) {
        return repo.loadPrice(id);   // slow query
    }

    public List<BigDecimal> findAll(List<Long> ids) {
        return ids.stream().map(this::findById).toList();
    }
}

Inside findAll, findById is called through this. @Cacheable works through a Spring proxy, and an internal call bypasses the proxy, so every call goes to the DB.

📖 Answer

When a controller calls priceService.findAll(...), it goes in through the proxy. findAll has no annotation, so the proxy just passes the call on to the real object. Inside the real object, this::findById is not the proxy, it's a plain Java call. The cache interceptor never runs.

Ways to fix it:

  1. Move the cacheable method into a separate bean. This is the cleanest way:
@Service
class PriceLoader {
    @Cacheable("prices")
    public BigDecimal load(long id) { return repo.loadPrice(id); }
}
  1. Inject your own proxy (@Lazy PriceService self). It works, but the code gets confusing.

  2. Switch to AspectJ mode (@EnableCaching(mode = AdviceMode.ASPECTJ)). It needs compile-time or load-time weaving and is rarely done.

@Transactional and @Async fail on internal calls for the same reason.