Home  >  Spring 4

Spring 4 @CacheConfig Annotation Example

By Arvind Rai, November 08, 2015
This page will walk through Spring 4 @CacheConfig annotation example. @CacheConfig is used to configure common cache related settings by annotating at class level. @CacheConfig has been introduced in Spring 4.1. All the methods annotated by @Cacheable gets default settings configured by @CacheConfig at class level. It reduces coding effort to configure @Cacheable attributes per method. We can override the default settings of @Cacheable by configuring its attributes per method. Here on this page, we will provide a complete example step by step.

Software used

Find the software used in demo.
1. Java 8
2. Spring 4.1
3. Gradle
4. Eclipse

Gradle file for Spring Boot


build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'SpringCache'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.springframework.boot:spring-boot-starter:1.2.7.RELEASE'
}  

Using @CacheConfig

@CacheConfig annotation is used at class level to share common cache related settings. All the methods of the class annotated with @Cacheable gets a common cache related settings provided by @CacheConfig. The attributes of @CacheConfig are cacheNames, cacheManager, cacheResolver and keyGenerator. We can override the class level cache related setting for a method using attributes of @Cacheable. Find a class annotated with @CacheConfig being used in our demo.
Student.java
package com.concretepage;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
@CacheConfig(cacheNames="mycacheone")
public class Student {
   @Cacheable
   public String getStudentName(int stdId) {
	System.out.println("execute getStudentName method...");
	if (stdId == 1) {
		return "Ramesh";
	} else {
		return "Mahesh";
	}
   }
   @Cacheable(value = "mycachetwo")
   public String getCity(int cityId) {
	System.out.println("execute getCity method...");
	if (cityId == 1) {
		return "Varanasi";
	} else {
		return "Allahabad";
	}
   }
} 

1. The class has two methods and both are annotated with @Cacheable annotation.
2. With the help of @CacheConfig at class level, we have configured cache name as mycacheone, so all the methods annotated with @Cacheable will use this cache name until we do not override.
3. getStudentName() method will use mycacheone cache name where as getCity() will use mycachetwo cache name because this method has overridden cache name using @Cacheable(value = "mycachetwo").
4. If the method is not annotated with @Cacheable, the result of that method will not be cached.

JavaConfig for SimpleCacheManager and ConcurrentMapCache


AppConfig.java
package com.concretepage; 
import java.util.Arrays;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.concretepage")
@EnableCaching
public class AppConfig  {
    @Bean
    public CacheManager cacheManager() {
       SimpleCacheManager cacheManager = new SimpleCacheManager();
       Cache cache1 = new ConcurrentMapCache("mycacheone");
       Cache cache2 = new ConcurrentMapCache("mycachetwo");
       cacheManager.setCaches(Arrays.asList(cache1, cache2));
       return cacheManager;
    }
} 

SimpleCacheManager : It works against given collection of caches. It is used for cache testing.
ConcurrentMapCache: We need to pass a cache name and it creates its instance.

Run Demo

To test the example, we will call getStudentName() and getCity() method three times, two times with same parameter value and third time with different parameter value. What we will observe in output is that while calling second time with same parameter value as first time call, the result of method is cached and it returns value from cache without executing method.
CacheDemo.java
package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class CacheDemo {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(AppConfig.class);
		ctx.refresh();

		Student student = ctx.getBean(Student.class);
		// calling getStudentName method first time.
		System.out.println(student.getStudentName(1));
		// calling getStudentName method second time with same parameter.
		//This time, method will not execute because result is cached with "mycacheone"
		System.out.println(student.getStudentName(1));
		// calling getStudentName method third time with different value.
		System.out.println(student.getStudentName(2));
		
		// calling getCity method first time.
		System.out.println(student.getCity(1));
		// calling getCity method second time with same parameter.
		//This time, method will not execute because result is cached with "mycachetwo"
		System.out.println(student.getCity(1));
		// calling getCity method third time with different value.
		System.out.println(student.getCity(2));
		ctx.close();
	}
} 
Find the output.
execute getStudentName method...
Ramesh
Ramesh
execute getStudentName method...
Mahesh
execute getCity method...
Varanasi
Varanasi
execute getCity method...
Allahabad 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS
comments powered by Disqus

Sitewide-Feb4of4234x60






Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us