# EhCache Example in Spring

In 
Published 2022-12-03

This tutorial explains to you how to use caching (EhCache) in Spring.

EhCache is a widely-used, Java cache that can be easily integrated with Java EE or Spring. In this example you can see how EhCache can be easily integrated with Spring framework. Ehcache is an open source, standards-based cache that boosts performance, offloads your database, and simplifies scalability. It's the most widely-used Java-based cache because it's robust, proven, full-featured, and integrates with other popular libraries and frameworks.

In order to use or test the EhCache with Spring, you have to create a simple Spring application and configure it to use Maven (Maven is used in my example).

Here is the pom.xml file dependencies:

Now we have to create the following classes:

package com.example.beans;
 
public class Product implements java.io.Serializable{
 
    private int price;
 
    public Product() {
        this.price = 0;     
    }
     
    public Product(int price) {
        this.price = price;     
    }
     
    public int getPrice() {
        return this.price;
    }
 
    public void setPrice(int price) {
        this.price = price;
    }
}
package com.example.service;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.example.beans.Product;
import com.example.dao.ProductDao;
 
@Service
public class ProductService {
 
    @Autowired
    private ProductDao productDao;
     
    public void getProductPrice(int productId) {
        try {
            Product p = productDao.getProduct(productId);
             
            System.out.println("Get Product price for productId("+productId+")="+p.getPrice());
             
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
package com.example.config;
 
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
 
import net.sf.ehcache.CacheManager;

@Configuration
@EnableCaching
@ComponentScan("com.example.*")
public class SpringContextConfig {
 
    @Bean
    public EhCacheCacheManager cacheManager(CacheManager cm) {
        return new EhCacheCacheManager(cm);
    }
     
    @Bean(name="ehCacheManagerFactoryBean")
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
        EhCacheManagerFactoryBean cacheManagerFactoryBean 
                   = new EhCacheManagerFactoryBean();
        cacheManagerFactoryBean.setConfigLocation (
                     new FileSystemResource("C:\\Java\\SPRING\\workspace\\SpringEhCacheExample\\src\\com\\example\\config\\ehcache.xml"));
         
        return cacheManagerFactoryBean;
    }
}
package com.example.dao;
 
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
 
import com.example.beans.Product;
 
@Repository
public class ProductDao {
     
    @Cacheable(value="cache1", key="#productId")
    public Product getProduct(int productId) throws InterruptedException {
        //Imagine you have here a SELECT into a database.
         
        Product product = new Product();
        product.setPrice(100);
         
        // Imagine you have to wait 3 seconds for a database call
        Thread.sleep(2000);
         
        return product;
    }
}
package com.example.main;
 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
import com.example.service.ProductService;
import com.example.config.SpringContextConfig;
 
public class Main {
 
     public static void main (String [] args) {
             
          System.out.println("Start Java Application ...");
             
          //The Spring context is configured from a Java Class for a Java Application 
          // (Not for a Web Application)
          // FileSystemXmlApplicationContext --> used when the context is defined in an xml file.
          AnnotationConfigApplicationContext context 
                  = new AnnotationConfigApplicationContext(SpringContextConfig.class);
                 
          System.out.println("Spring context created ...");
              
          ProductService productService = context.getBean(ProductService.class);
           
          final long time1 = System.currentTimeMillis();
           
          productService.getProductPrice(10);
          final long time2 = System.currentTimeMillis();
          System.out.println("Time1 for product: " + ((time2 - time1) / 1000) + "s");
           
          productService.getProductPrice(10);
          final long time3 = System.currentTimeMillis();
          System.out.println("Time2 for product: " + ((time3 - time2) / 1000) + "s");
         
          context.close();
       }
}

... and configure the EhCache using the following XML configuration file:

<!--?xml version="1.0" encoding="UTF-8"?-->
<ehcache>
   <cache name="cache1" maxbyteslocalheap="100m" timetoliveseconds="3600">       
   </cache>
</ehcache>

This file is the following in my example: "C:\Java\SPRING\workspace\SpringEhCacheExample\src\com\example\config\ehcache.xml"

When I run the application I receive:

As you can see the 2nd call will not use the DAO class. This is because the cache is used.