Spring @CacheEvict Example

By Arvind Rai, November 16, 2021
This page will walk through Spring @CacheEvict example
1. Spring @CacheEvict annotation is used to evict cache.
2. The @CacheEvict is used at method level.
3. The @Cacheable annotation sets the value in cache and on the contrary @CacheEvict evicts the cache.
4. At one method we can use @Cacheable to cache result and at another method we can use @CacheEvict to evict cache.
5. The @CacheEvict annotation is introduced in Spring 3.1.

The @CacheEvict has following attributes.
1.
String[] cacheNames 
Cache names to evict.
2.
String[] value 
Alias for cacheNames.
3.
String key 
SpEL expression for computing the key dynamically.
4.
String keyGenerator 
The bean name of the custom KeyGenerator to use.
5.
String cacheManager 
The bean name of the custom CacheManager. It is used to create default CacheResolver if none is set already.
6.
String cacheResolver 
The bean name of the custom CacheResolver to use.
7.
String condition 
SpEL expression used for making the cache eviction operation conditional.
8.
boolean allEntries 
If true, all the entries inside the cache are removed.
9.
boolean beforeInvocation 
If true, the cache eviction will occur before the method is invoked.

Using @CacheEvict

Employee.java
package com.concretepage;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
public class Employee {
  @CacheEvict(value = "emp", allEntries=true)
  public void setEmployee(int empId){
	System.out.println("execute setEmployee method..");
  }
  @Cacheable("emp") 
  public String getEmployee(int empId){
	System.out.println("execute getEmployee method..");
	if(empId==1){			
		return "Atul";
	}else{
		return "Sudhir";
	}
  }
} 
In the given Employee class we have two methods setEmployee() and getEmployee(). We have annotated getEmployee() with @Cacheable and it will set method output in cache. The setEmployee() method is annotated with @CacheEvict and it will evict values from cache.
Find other files to run the demo application.
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
	<defaultCache eternal="true" maxElementsInMemory="100"
		overflowToDisk="false" />
	<cache name="emp" maxElementsInMemory="10000" eternal="true"
		overflowToDisk="false" />
</ehcache> 
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/cache
           http://www.springframework.org/schema/cache/spring-cache.xsd">
 
        <cache:annotation-driven />
	<bean id="employee" class="com.concretepage.Employee"/>
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache"/>
	<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="classpath:ehcache.xml"/>

</beans> 
Now run the application.
SpringDemo.java
package com.concretepage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
    public static void main(String... args) {
    	AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            Employee employee=(Employee) context.getBean("employee");
            
            //calling getEmployee method first time.
            System.out.println(employee.getEmployee(1));
            
            //calling getEmployee method second time. This time, method will not execute.
            System.out.println(employee.getEmployee(1));
            
            //calling setEmployee method to evict the cache value 
            employee.setEmployee(1);
            
            //calling getEmployee method third time. This time, method will  execute again.
            System.out.println(employee.getEmployee(1));
     } 
} 
In the above code, we have called getEmployee() method many times. First time getEmployee() method runs and sets result in cache named emp. Second time getEmployee() does not run because there is value in cache. Now call setEmployee() to evict the cache value. Again call getEmployee() method and this time it will run because cache value is empty. Find the output.
Output
execute getEmployee method..
Atul
Atul
execute setEmployee method..
execute getEmployee method..
Atul 

Reference

Annotation Type CacheEvict
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us