Spring @CachePut Annotation Example

By Arvind Rai, March 07, 2023
This page will provide Spring @CachePut annotation example using JavaConfig. This annotation is used to put value in cache for the given cache name and key. In contrary to @Cacheable annotation, the method annotated with @CachePut runs for every call and put results in cache. The @CachePut has elements such as cacheNames, value, condition, key, unless, keyGenerator etc. To compute the key, method parameters are used by default, but a SpEL expression can be provided via the key attribute.
Now @CachePut is used as follows.
@CachePut(value = "mycache", key="#id")
public Book updateBook(int id, String bookName) {} 

cacheNames: Name of the caches in which method result are stored.
value: Alias for cacheNames.
condition: Spring SpEL expression to make conditional caching.
key: SpEL to compute key dynamically.
keyGenerator: Bean name for custom KeyGenerator.
unless: SpEL to veto method caching.

Find the complete example step by step.

Technologies Used

Find the technologies being used in our example.
1. Java
2. Spring
3. Gradle
4. Eclipse

Gradle File

build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'spring-cache'

repositories {
    mavenCentral()
}
dependencies {
    compile 'org.springframework.boot:spring-boot-starter:2.0.4.RELEASE'
} 

Using @CachePut

To use @CachePut, we have created a method to update book. The method is annotated with @CachePut. We have another method to get book that is annotated with @Cacheable annotation.
BookApp.java
package com.concretepage;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class BookApp {
	@CachePut(value = "mycache", key="#id")
	public Book updateBook(int id, String bookName) {
		System.out.println("Executing updateBook method...");	
		Book book = new Book();
		book.setId(id);
		book.setName(bookName);
		return book;
	}
	@Cacheable(value = "mycache", key="#id")
	public Book getBook(int id) {
		System.out.println("Executing getBook method...");
		Book book = new Book();
		book.setId(id);		
		book.setName("Mahabharat");
		return book;
	}
} 
Here we have created cache name as mycache and key as given book id in method parameters. When we call getBook() method, the result of it will be cached for the given book id in mycache and now onwards the calling of this method for that book id will not execute and return cached value. If we want to change the cache value, we need to call updateBook() method.
Book.java
package com.concretepage;
public class Book {
	private int id;
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
} 

JavaConfig

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 cache = new ConcurrentMapCache("mycache");
       cacheManager.setCaches(Arrays.asList(cache));
       return cacheManager;
    }
} 

Run Demo

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();
		BookApp bookApp = ctx.getBean(BookApp.class);
		int id = 10;
		//Calling getBook method first time for an id.
		System.out.println(bookApp.getBook(id).getName());
		//Calling getBook method second time for same id.
		//This time, method will not execute because result is cached with "mycache" for that id.
		System.out.println(bookApp.getBook(id).getName());
		//Calling updateBook method to change cache value for that id.
                bookApp.updateBook(id, "Ramayan");
		//Calling getBook method again for that id. Method will not execute but cache value will change.
		System.out.println(bookApp.getBook(id).getName());
		ctx.close();
	}
} 
Find the output.
Executing getBook method...
Mahabharat
Mahabharat
Executing updateBook method...
Ramayan 

References

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us