花了很长时间弄清楚如何在 Spring 5 (Springboot 2.x) 项目的 jar 文件之外外部化 ehCache 3 ehcache.xml。这很重要,这样可以调整 ehcache 设置而无需重新部署项目。
问问题
391 次
1 回答
1
只是分享一个使用 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()));
}
}
于 2018-11-26T03:29:14.870 回答