【问题标题】:Is it possible to Split an ehcache config file?是否可以拆分 ehcache 配置文件?
【发布时间】:2012-06-27 12:13:15
【问题描述】:
我正在编写一个用于 Spring 和 Ehcache 的 jar。 Spring 要求为每个元素定义一个缓存,因此我计划为 jar 定义一个 Ehcache,最好作为 jar 中的资源,可以导入到应用程序的主 Ehcache 配置中。然而,我对example Ehcache config file 的阅读和我的谷歌搜索并没有找到任何导入子 Ehcache 配置文件的方法。
有没有办法导入一个子 Ehcache 配置文件,或者有没有其他方法可以解决这个问题?
【问题讨论】:
标签:
spring
configuration
ehcache
【解决方案1】:
我做了类似的事情(替换我的 Ehcache xml 文件中的一些占位符 - 如果您愿意,导入语句或多或少是一个占位符)是从 Springs EhCacheManagerFactoryBean 扩展(或多或少复制)并即时创建最终的 Ehcache xml 配置文件。
要在afterPropertiesSet() 中创建CacheManager 实例,您只需交出指向您的配置的InputStream。
@Override
public void afterPropertiesSet() throws IOException, CacheException {
if (this.configLocation != null) {
InputStreamSource finalConfig = new YourResourceWrapper(this.configLocation); // put your custom logic here
InputStream is = finalConfig.getInputStream();
try {
this.cacheManager = (this.shared ? CacheManager.create(is) : new CacheManager(is));
} finally {
IOUtils.closeQuietly(is);
}
} else {
// ...
}
// ...
}
对于我的过滤内容,我在内部使用了ByteArrayResource 来保留最终配置。
data = IOUtils.toString(source.getInputStream()); // get the original config (configLocation) as string
// do your string manipulation here
Resource finalConfigResource = new ByteArrayResource(data.getBytes());
对于“真正的”模板,也可以考虑使用真正的模板引擎,如 FreeMarker(Spring 支持)来做更多花哨的事情。