0
0
Spring Bootframework~5 mins

@EnableCaching annotation in Spring Boot

Choose your learning style9 modes available
Introduction

The @EnableCaching annotation turns on caching support in a Spring Boot app. It helps store data temporarily to make your app faster.

When you want to speed up repeated data fetching in your app.
When you have expensive operations like database calls or API requests.
When you want to reduce load on your backend services.
When you want to improve user experience by showing results faster.
Syntax
Spring Boot
@EnableCaching
@Configuration
public class CacheConfig {
    // cache setup here
}
Place @EnableCaching on a configuration class to activate caching.
It works together with cache annotations like @Cacheable on methods.
Examples
Basic setup to enable caching in your Spring Boot app.
Spring Boot
@EnableCaching
@Configuration
public class AppConfig {
}
Enable caching directly in the main application class.
Spring Boot
@SpringBootApplication
@EnableCaching
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
Sample Program

This example shows how @EnableCaching activates caching. The first call to getData("apple") prints the fetching message and returns data. The second call with the same argument returns cached data without printing the fetching message.

Spring Boot
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

@SpringBootApplication
@EnableCaching
public class CacheDemoApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(CacheDemoApplication.class, args);
        var service = context.getBean(DataService.class);

        System.out.println(service.getData("apple"));
        System.out.println(service.getData("apple"));
    }
}

@Service
class DataService {
    @Cacheable("fruits")
    public String getData(String name) {
        System.out.println("Fetching data for " + name);
        return "Data for " + name;
    }
}
OutputSuccess
Important Notes

Without @EnableCaching, cache annotations like @Cacheable won't work.

Caching improves speed but be careful with stale data; clear cache when needed.

Summary

@EnableCaching turns on caching in Spring Boot apps.

Use it with @Cacheable to store method results temporarily.

It helps make apps faster by avoiding repeated work.