Search code examples
springspring-bootehcachejcache

Set Ehcache's persistence directory programmatically on Spring Boot


I'm setting my caches programmatically on Spring Boot and I need to set the persistence directory.

According to Ehcache's documentation, this must be done globally at the CachingProvider level:

CachingProvider cachingProvider = Caching.getCachingProvider();
EhcacheCachingProvider ehcacheProvider = (EhcacheCachingProvider) cachingProvider; 

DefaultConfiguration configuration = new DefaultConfiguration(ehcacheProvider.getDefaultClassLoader(),
  new DefaultPersistenceConfiguration(getPersistenceDirectory())); 

CacheManager cacheManager = ehcacheProvider.getCacheManager(ehcacheProvider.getDefaultURI(), configuration);

The problem is, the mechanism offered by Spring to configure caches, JCacheManagerCustomizer, works at the CacheManager level, by then it's too late to set the persistence directory.

So, my question is, what is the best way to achieve this? I do not want to use ehcache.xml to do this, I inject a bunch of configurations on my application and it's support of dynamic configuration is too limited to my needs.


Solution

  • So at the moment, before someone points me to the right direction, what I'm doing is:

    ...
    import org.springframework.cache.CacheManager;
    import org.springframework.cache.jcache.JCacheCacheManager;
    ...
    @Configuration
    @EnableCaching
    public class CacheConfiguration {
    ...
    @Bean
        public CacheManager getCacheManager() {
            var cachingProvider = (EhcacheCachingProvider) Caching.getCachingProvider();
    
            DefaultConfiguration configuration = new DefaultConfiguration(cachingProvider.getDefaultClassLoader(),
                    new DefaultPersistenceConfiguration(directory.toFile()));
    
            var cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), configuration);
            cacheManager.createCache(...)
            return new JCacheCacheManager(cacheManager);
        }
    ...
    }
    

    I feel this is not quite right, it seems I'm bypassing Spring by getting a reference to the CachingProvider. I mean, Spring detects the Ehcache provider on the classpath, shouldn't it inject the CachingProvider for me?