3

I'm writing a jar intended to be used with Spring and Ehcache. Spring requires that there be a cache defined for each element, so I was planning to have an Ehcache defined for the jar, preferably as a resource in the jar that could be imported into the primary Ehcache configuration for the app. However, my reading of the example Ehcache config file and my Google searches have not turned up any way to import a sub Ehcache config file.

Is there a way to import a sub Ehcache config file, or is there some other way to solve this problem?

C. Ross
  • 31,137
  • 42
  • 147
  • 238
  • Related (possible dup?): [Is it possible to use multiple ehcache.xml (in different projects, same war)?](http://stackoverflow.com/q/8834993/16487) – C. Ross Jun 27 '12 at 13:21

1 Answers1

1

What I did to do something similar (replace some placeholders in my Ehcache xml file - a import statement is more or less a placeholder if you will) is to extend (more or less copy to be honest) from Springs EhCacheManagerFactoryBean and create the final Ehcache xml config file on the fly.

For creating the CacheManager instance in afterPropertiesSet() you just hand over a InputStream which points to your config.

@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 {
        // ...
    }
    // ...
}

For my filtering stuff I internally used a ByteArrayResource to keep the final config.

data = IOUtils.toString(source.getInputStream()); // get the original config (configLocation) as string
// do your string manipulation here
Resource finalConfigResource =  new ByteArrayResource(data.getBytes());

For "real" templating one could also think of using a real template engine like FreeMarker (which Spring has support for) to do more fancy stuff.

jeha
  • 10,562
  • 5
  • 50
  • 69