Java 将ehCache 3 ehCache.xml放在Springboot 2(Spring 5)项目的jar文件之外

Java 将ehCache 3 ehCache.xml放在Springboot 2(Spring 5)项目的jar文件之外,java,spring,spring-boot,ehcache-3,Java,Spring,Spring Boot,Ehcache 3,我花了相当长的时间研究如何在Spring5Springboot2.x项目的jar文件之外具体化ehCache 3ehcache.xml。这一点很重要,这样就可以在不重新部署项目的情况下调整ehcache设置。只要共享一个使用Java 8的解决方案,以防其他人面临此挑战: package com.myproject.config; import java.net.URISyntaxException; import java.nio.file.Paths; import javax.cache.C

我花了相当长的时间研究如何在Spring5Springboot2.x项目的jar文件之外具体化ehCache 3ehcache.xml。这一点很重要,这样就可以在不重新部署项目的情况下调整ehcache设置。

只要共享一个使用Java 8的解决方案,以防其他人面临此挑战:

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()));
    }
}