How to configure Jcache with Ecache as Provider in Spring application-context.xml?

2.8k views Asked by At

Spring documentation provides below information.

<bean id="cacheManager"
   class="org.springframework.cache.jcache.JCacheCacheManager"
   p:cache-manager-ref="jCacheManager"/>

<!-- JSR-107 cache manager setup  -->
<bean id="jCacheManager" .../>

I want to know exactly how to configure this jcacheManager bean (with EhCache as provider) in spring application context xml.

I have already configured dependency, as below, in pom.xml which is fine.

<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>jcache</artifactId>
    <version>1.0.1</version>
    <exclusions>
        <exclusion>
            <artifactId>slf4j-api</artifactId>
            <groupId>org.slf4j</groupId>
        </exclusion>
    </exclusions>
</dependency> 
2

There are 2 answers

0
Rocky Hu On

It's not convenient for us to integrate Ehache3.x with Spring4.x now. Spring boot does it, and it rewrites some codes:

<bean id="cacheManager"
   class="org.springframework.cache.jcache.JCacheCacheManager"

in Spring boot, it's:

@Bean
    public JCacheCacheManager cacheManager(CacheManager jCacheCacheManager) {
        return new JCacheCacheManager(jCacheCacheManager);
    }

and it needs a javax.cache.CacheManager instance,

<!-- JSR-107 cache manager setup  -->
<bean id="jCacheManager" .../>

Ehcache have no in-depth introduction for us.

Spring boot does like:

@Bean
    @ConditionalOnMissingBean
    public CacheManager jCacheCacheManager() throws IOException {
        CacheManager jCacheCacheManager = createCacheManager();
        List<String> cacheNames = this.cacheProperties.getCacheNames();
        if (!CollectionUtils.isEmpty(cacheNames)) {
            for (String cacheName : cacheNames) {
                jCacheCacheManager.createCache(cacheName, getDefaultCacheConfiguration());
            }
        }
        customize(jCacheCacheManager);
        return jCacheCacheManager;
    }

It's a normal operation to create javax.cache.CacheManager just follows the Ehcache document.

0
Stephane Nicoll On

It really depends how you want to configure it. If you're using Spring Boot 1.3, it will be automatically created for you. Maybe you could have a look to the source of JCacheCacheConfiguration?

You can retrieve the default javax.cache.CacheManager via Caching.getCachingProvider().getCacheManager()