Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 1 of 10 · Caching, Async & Scheduling
Interview question

How does caching work in Spring Boot with @EnableCaching and @Cacheable? स्प्रिंग बूट में @EnableCaching और @Cacheable के साथ कैशिंग कैसे काम करती है?

Answer

Spring's caching abstraction lets you cache the result of an expensive method call transparently, without changing the method's logic. Adding @EnableCaching to a configuration class activates Spring's caching infrastructure, and @Cacheable("cacheName") on a method tells Spring to check the cache first — if a value exists for the given arguments (the cache key), the method body is skipped entirely and the cached value is returned.

Under the hood, Spring wraps the bean in a proxy that intercepts calls to the annotated method, so caching only works on calls made through the Spring-managed bean (external calls), not on self-invocation within the same class, similar to the @Transactional proxy limitation.

@Service
public class ProductService {
    @Cacheable("products")
    public Product getProduct(Long id) {
        return productRepository.findById(id).orElseThrow(); // only runs on cache miss
    }
}

स्प्रिंग की कैशिंग एब्सट्रैक्शन आपको किसी महंगे मेथड कॉल के परिणाम को पारदर्शी रूप से कैश करने देती है, बिना मेथड के लॉजिक को बदले। @EnableCaching जोड़ने से स्प्रिंग का कैशिंग इंफ्रास्ट्रक्चर सक्रिय होता है, और मेथड पर @Cacheable("cacheName") स्प्रिंग को पहले कैश जाँचने के लिए कहता है।

अंदर से, स्प्रिंग बीन को एक प्रॉक्सी में लपेटता है जो एनोटेटेड मेथड की कॉल्स को इंटरसेप्ट करता है, इसलिए कैशिंग केवल स्प्रिंग-मैनेज्ड बीन के ज़रिए की गई कॉल्स पर काम करती है, उसी क्लास के अंदर सेल्फ-इनवोकेशन पर नहीं।

@Service
public class ProductService {
    @Cacheable("products")
    public Product getProduct(Long id) {
        return productRepository.findById(id).orElseThrow();
    }
}

Was this answer clear?