Place ehCache 3 ehcache.xml outside of the Springboot 2 (Spring 5 ) project's jar file

576 Views Asked by At

Had spent quite some time figuring out how to externalize ehCache 3 ehcache.xml outside of the jar file of an Spring 5 (Springboot 2.x) project. This is important so that ehcache settings could be tweaked without having to redeploy the project.

1

There are 1 best solutions below

0
On

Just sharing a solution that worked using Java 8 in case anybody else faces this challenge:

package com.myproject.config;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import javax.cache.Caching;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Configures ehCache.
 * 
 * @author 
 *
 */
@Configuration
@EnableCaching
public class CacheConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(CacheConfiguration.class);
    @Value("${myproject.cache.ehcache.xml.fullpath:/dir/outside/of/project/config/ehcache.xml}")
    private String ehcacheXmlFullPath;

    @Bean
    public CacheManager cacheManager() throws URISyntaxException {
        // To get from the classpath: getClass().getResource("/ehcache.xml").toURI()
        return new JCacheCacheManager(Caching.getCachingProvider().getCacheManager(Paths.get(ehcacheXmlFullPath).toUri(),
                getClass().getClassLoader()));
    }
}