Annotation @CachePut example

In this post under Spring Caching, I will introduce you to “@CachePut” Spring annotation.

Similar to “@Cacheable” annotation it can be applied at class and method level.

The difference between “@Cacheable” and “@CachePut” is that “@Cacheable” can be used to both get value from the cache and put value in the cache but “@CachePut” is used only to put value in the cache and no get.

The purpose of this method is store the result of a method in the cache.

So the method on which this annotation is applied should return the result otherwise the cache will not be able to get the result to put it in the cache.

Lets see an example.

For our example we will use the below class

Calculator

package caching.package13;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class Calculator {
int sum = 0;
@CachePut(cacheNames = "sum")
public int calculate() {
for(int i = 1; i < 10000; i++) {
sum = sum + i;
}
return sum;
}
}

In the above code, the method “calculate” is annotated with “@CachePut” and the cache region name given is “sum”.

Now whenever we call this method, the cache is updated with the result of the method.

Below is the main class for your reference.

Main class

package caching.package13;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@EnableCaching
@Configuration
@ComponentScan(basePackages = "caching.package13")
public class Example13 {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(Example13.class);
Calculator calculator = annotationConfigApplicationContext.getBean(Calculator.class);
calculator.calculate();
}
}

Leave a Reply