Ehcache: Java Based Cache in Spring Boot

Ehcache: Java Based Cache in Spring Boot

Most of the time, when we need to retrieve the same piece of data repeatedly from a data store, we generally try to cache the data to an in-memory cache. One such library we use when our data is lightweight is Ehcache. In this article, we shall see how to implement Ehcache in Spring boot by creating bean.

Step 1: Adding Dependency to 'pom.xml'


Step 2: Creating the Bean Class to Creating Ehcache instance

public class EhCacheBean {

    private Cache<String, String> ehCache;

    public void init() {
        CacheManager cacheManager = CacheManagerBuilder


        ehCache= cacheManager.createCache("applicationCache", CacheConfigurationBuilder
                        String.class, String.class,


    Cache<String, String> getSpmCache() {
        if (ehCache== null) {
        return ehCache;


Step3:  Example to Add values to Cache and retrieve the Value from The cache.

At first Auto Wire the Cache instance in your service class like this

private Cache<String,String> appCache;

At next we can use the 'appCache' Variables to add the value like this


And to retrieve


Finally to check if the key exist  and remove the item  we can use these