JCache providers behind Spring's cache abstraction
Connect JSR 107 to Spring Cache and compare annotations, provider selection, expiry, and store-by-value behavior in a Spring Boot application.
Spring Cache decides when to use a cache. A JCache provider decides how entries are stored and expired. The separation matters when I switch providers or need a portable cache API in shared code.
The examples use Spring Boot 3.x with Java 17 or 21 and the JCache 1.1 API.
Why JCache has a separate API
Caching libraries started with different ways to retrieve a cache, apply expiry, and configure entry listeners. JSR 107 defines a shared API under javax.cache. It retained that package name through the Jakarta EE namespace transition.
A CachingProvider creates a CacheManager. The manager creates, retrieves, and closes named caches. A Cache<K, V> handles entries, while policies and listeners control expiration and entry events. Spring’s JCacheCacheManager adapts a JCache manager to Spring’s own cache abstraction.
flowchart TD
APP["Application annotations"] --> SPRING["Spring Cache adapter"]
APP -->|"Direct access"| API["JCache API"]
SPRING --> API
API --> P["CachingProvider"]
P --> M["CacheManager"]
M --> C["Named cache and expiry policy"]
You can use Caffeine’s JCache adapter for an in-process cache, Ehcache when its configuration and storage choices fit, or a Redis-backed implementation such as Redisson for a shared cache. Each provider has its own tuning and deployment model.
How the two annotation models differ
| Operation | Spring Cache | JCache |
|---|---|---|
| Load and cache a result | @Cacheable with SpEL conditions | @CacheResult, with optional exception caching |
| Update a cache entry | @CachePut uses the method result | @CachePut uses an argument marked @CacheValue |
| Remove one entry | @CacheEvict | @CacheRemove, with options for exception outcomes |
| Clear a cache | @CacheEvict(allEntries = true) | @CacheRemoveAll |
| Share defaults | @CacheConfig | @CacheDefaults |
| Select a key | SpEL such as #id | Parameter annotations such as @CacheKey |
I use one annotation family per method. Otherwise two interceptors could issue unrelated cache operations around a single call. Choosing JCache as the backend still allows application methods to use Spring’s annotations.
Choosing a provider and registering a cache
Start with the JCache API and one provider. The alternatives in the build file are options for different deployments. If more than one provider is present, set the provider explicitly so startup does not depend on classpath discovery order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// build.gradle.kts
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-cache")
// JSR 107 (JCache) API
implementation("javax.cache:cache-api:1.1.1")
// Provider option 1: Caffeine's JCache module
implementation("com.github.ben-manes.caffeine:jcache:3.1.8")
// Provider option 2: Ehcache 3 with its Jakarta classifier
// implementation("org.ehcache:ehcache:3.10.8:jakarta")
// Provider option 3: Redisson for a distributed cache
// implementation("org.redisson:redisson-spring-boot-starter:3.37.0")
}
1
2
3
4
5
6
# src/main/resources/application.yml
spring:
cache:
type: jcache
jcache:
provider: com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider
The customizer creates a cache when the manager is configured. It controls expiry and enables statistics. A local cache can use store-by-reference to avoid copying. In that mode the caller may see changes to a mutable cached object. Prefer immutable values or keep store-by-value if a snapshot matters. Check the provider’s rules here, especially for remote or off-heap storage.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// src/main/java/com/example/cache/config/JCacheConfig.java
package com.example.cache.config;
import java.util.concurrent.TimeUnit;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class JCacheConfig {
public static final String PRODUCT_CACHE = "products";
@Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
return cacheManager -> {
MutableConfiguration<Object, Object> config = new MutableConfiguration<>()
.setExpiryPolicyFactory(
CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 10))
)
.setStoreByValue(false) // Store references in the local cache to avoid copying
.setStatisticsEnabled(true); // Enable cache statistics
if (cacheManager.getCache(PRODUCT_CACHE) == null) {
cacheManager.createCache(PRODUCT_CACHE, config);
}
};
}
}
Applying the cache to a repository lookup
The service looks up a product and caches the result under its ID. An intercepted call hits the repository on a miss and can return a cached value on a later hit. The stack still needs a policy for writes. A product update may require eviction, a forced refresh, or a short expiry window.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// src/main/java/com/example/cache/service/ProductService.java
package com.example.cache.service;
import com.example.cache.config.JCacheConfig;
import com.example.cache.domain.Product;
import com.example.cache.repository.ProductRepository;
import javax.cache.annotation.CacheDefaults;
import javax.cache.annotation.CacheKey;
import javax.cache.annotation.CachePut;
import javax.cache.annotation.CacheRemove;
import javax.cache.annotation.CacheResult;
import javax.cache.annotation.CacheValue;
import org.springframework.stereotype.Service;
@Service
@CacheDefaults(cacheName = JCacheConfig.PRODUCT_CACHE)
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@CacheResult
public Product findById(@CacheKey Long productId) {
return productRepository.findById(productId)
.orElseThrow(() -> new IllegalArgumentException("Product not found: " + productId));
}
@CachePut
public void updateCache(@CacheKey Long productId, @CacheValue Product updated) {
productRepository.save(updated);
}
@CacheRemove
public void deleteProduct(@CacheKey Long productId) {
productRepository.deleteById(productId);
}
}
Calls from another Spring bean pass through the cache proxy. A self-invocation can skip it. I verify caching through the managed bean rather than by creating the service directly in a unit test.
Picking the interface the application needs
For a Spring-only service, Spring Cache offers convenient keys, conditions, and integration. JCache helps when another Java framework or a shared module needs the same cache API. For a remote cache, measure latency, serialization, and failure behavior with the deployed provider. Before rollout, validate that expiry, eviction, and key generation still fit the use case. Enable a controlled metric or log to distinguish a cache hit from a repository call while checking behavior.