Spring & Guava Cache

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')

public class CacheConfig implements CachingConfigurer {

	public final static String CACHE = "cache";

	private static final Logger LOGGER = LoggerFactory.getLogger(CacheConfig.class);

	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());
		return cacheManager;

	public KeyGenerator keyGenerator() {
		return new SimpleKeyGenerator();

// mark method with @Cacheable annotation
public class CacheService {

	private BooksService bookService;

	public List<Book> getBooks() {
		return bookService.getBooks();

// You can clear cache like this
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);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s