Check the excellent guide here about Cache in Spring. Below you can find similar code. Also check the official docs.
// compile ('org.springframework:spring-context-support:4.0.7.RELEASE')
@Configuration
@EnableCaching
public class CacheConfig implements CachingConfigurer {
public final static String CACHE = "cache";
private static final Logger LOGGER = LoggerFactory.getLogger(CacheConfig.class);
@Bean
@Override
public CacheManager cacheManager() {
LOGGER.info("Initializing simple Guava Cache manager.");
SimpleCacheManager cacheManager = new SimpleCacheManager();
GuavaCache discoveryCache = new GuavaCache(CACHE,
CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES).build());
cacheManager.setCaches(Arrays.asList(discoveryCache));
return cacheManager;
}
@Bean
@Override
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator();
}
}
// mark method with @Cacheable annotation
@Component
public class CacheService {
@Inject
private BooksService bookService;
@Cacheable(CacheConfig.CACHE)
public List<Book> getBooks() {
return bookService.getBooks();
}
}
// You can clear cache like this
@Controller
@RequestMapping("/")
public class ClearCacheController {
@CacheEvict(value = CacheConfig.CACHE, allEntries = true)
@RequestMapping(value = "/clearCache", method = RequestMethod.GET)
public ResponseEntity<String> clearCache() {
return new ResponseEntity<String>("Cache Cleared", HttpStatus.OK);
}
}