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



花了相当长的时间研究如何将ehCache 3 ehCache.xml外部化到Spring 5(Springboot 2.x(项目的jar文件之外。这一点非常重要,这样就可以在不重新部署项目的情况下调整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()));
}
}

最新更新