Video in progress
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:
- 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); }
}
-
Inject your own proxy (
@Lazy PriceService self). It works, but the code gets confusing. -
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.
Sign up to mark studied questions and save your progress.