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.
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;
}
}