Skip to main content

Posts

Showing posts with the label AOP

Redis Cache Issue – Why @Cacheable Didn’t Work (and Fix)

 Hi 👋, I’m Anandharaj. Today’s learning is about Redis Cache in Spring Boot.   We faced an interesting issue at work (Project) where @Cacheable didn’t behave as expected. 👉 The key takeaway: Avoid self-invocation when using @Cacheable methods. Let me explain with code examples below. ❌ Non‑Working Code (Self‑Invocation Issue) In the below snippet, the processData() method calls another @Cacheable method internalGetData() inside the same class.  Because it’s an internal call, Spring’s proxy is bypassed, so caching never happens. ✅ Working Code (Fixed with separate bean) To fix it, we separated the cached method into another Spring-managed bean (another class). Now the call goes through the proxy and caching works as expected. 💡 Key Takeaways: ✔️ Avoid calling @Cacheable methods from within the same class. ✔️ Move the cached method to another Spring bean. ✔️ This ensures the proxy logic and caching work correctly.