Ehcache is a Java cache library that Spring can use as the storage behind its cache abstraction. You annotate methods with @Cacheable, and Ehcache keeps the results in heap, off-heap memory or on disk, so repeated calls skip the database or the remote service. In current projects you use Ehcache 3 through its JCache (JSR-107) support, because the old Ehcache 2 integration is no longer part of Spring.
This article shows how Ehcache fits into Spring caching, how to configure it in Spring Boot, and when another provider is a better choice.
Spring Framework defines a cache abstraction: annotations such as @Cacheable, @CachePut and @CacheEvict, backed by a CacheManager. The abstraction does not store anything itself. A provider does, and Ehcache is one of the supported providers, together with Caffeine, Redis and others.
The flow for a @Cacheable method is:
Ehcache decides how many entries are kept, where they live, and when they expire.
Add the starter, the JCache API and Ehcache. Spring Boot manages the versions:
Point Spring Boot at the Ehcache configuration in application.properties:
Then define the caches in src/main/resources/ehcache.xml:
This cache keeps up to 1,000 entries on the heap, spills to 20 MB of off-heap memory, and expires entries ten minutes after they are written. Values stored off-heap or on disk must be serialisable, so make Product implement Serializable.
Enable caching once, then annotate service methods:
@Cacheable reads, @CachePut always runs the method and refreshes the entry, and @CacheEvict removes it. Spring applies these through proxies, so they work only on calls that cross the bean boundary. A method calling another method of the same class bypasses the cache.
| Need | Good fit |
|---|---|
| Fast in-process cache, simple setup | Caffeine |
| In-process cache with off-heap or disk tiers | Ehcache |
| Cache shared by several application instances | Redis or another distributed cache |
Because Ehcache is in-process by default, each application instance has its own copy. After a write on one instance, the others can still serve stale data until the entry expires. Use short expiry times, or a distributed cache, when that matters.
No. Use Ehcache 3, which Spring integrates through JCache. Ehcache 2 used a different package and API.
Common causes are a missing @EnableCaching, a call from within the same class, a method that is not public, or a key that changes on every call.
Only when they leave the heap, for example with off-heap or disk tiers, or with clustering. Heap-only caches can hold any object.
Yes, through the JCache integration of Hibernate. That is separate from the Spring cache abstraction.
Ehcache is a cache provider for the Spring cache abstraction. Use Ehcache 3 through JCache, configure caches in ehcache.xml, and apply @Cacheable, @CachePut and @CacheEvict in your services. Pick Caffeine for the simplest local cache and Redis when instances must share data.