Spring Caching with JCache
JCache is a Java EE specification which missed the Java EE 7 train, but it is ready for Java EE 8 now.
EhCache, Infinispan etc provide implementations of JCache 1.0 specification.
Spring core provides a bridge between JCache and Spring Caching abstraction.
Enable Caching
Add
@EnableCaching(mode=AdviceMode.ASPECTJ)
annotation on the configuration class if you are using Java based configuration.@Configuration ... @EnableCaching(mode=AdviceMode.ASPECTJ) public class JpaConfig {...}
Then, specify a
CacheManager
provider in your configuration. There is a JCacheCacheManager
provided by Spring.
But also specify JCache will use EhCache as backend implementation.
@Override @Bean public CacheManager cacheManager() { JCacheCacheManager cacheManager = new JCacheCacheManager(); cacheManager.setCacheManager(new JCacheManager( new JCacheCachingProvider(), ehcache(), null, null)); return cacheManager; } private net.sf.ehcache.CacheManager ehcache() { return new net.sf.ehcache.CacheManager(); } @Override @Bean public KeyGenerator keyGenerator() { return new SimpleKeyGenerator(); }
Do not forget to add the ehcache dependency in your Maven pom.xml file.
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>jcache</artifactId> </dependency>
Note, aslo added a Ehcache Jcache dependency.
Code sample
Check out the sample codes.
And explore the spring-cache-jcache folder.
评论