Spring Ehcache 3.x configuration via XML

1.5k Views Asked by At

I'm trying to inject Ehcache (v3.9) javax.cache.CacheManager (JSR-107 JCache API) using Spring XML context. Initial attempt:

<bean id="cacheManager" factory-bean="cachingManagerProvider" factory-method="getCacheManager">
    <constructor-arg name="uri" type="java.net.URI" value="classpath:/WEB-INF/ehcache.xml" />
    <constructor-arg name="classLoader" type="java.lang.ClassLoader" ><null /></constructor-arg>
</bean>

<bean id="cachingManagerProvider" class="org.ehcache.jsr107.EhcacheCachingProvider" />

fails with java.lang.IllegalArgumentException: Could not retrieve URI for class path resource [WEB-INF/ehcache.xml]: class path resource [WEB-INF/ehcache.xml] cannot be resolved to URL because it does not exist

I managed to do it only using adapter class:

import java.io.IOException;

import javax.cache.CacheManager;
import javax.cache.spi.CachingProvider;

import org.springframework.core.io.Resource;

public class CacheManagerFactory {
    private final Resource configurationLocation;
    private final CachingProvider cachingProvider;

    public CacheManagerFactory(CachingProvider cachingProvider, Resource configurationLocation) {
        this.configurationLocation = configurationLocation;
        this.cachingProvider = cachingProvider;
    }

    public CacheManager getCacheManager() {
        try {
            return this.cachingProvider.getCacheManager(this.configurationLocation.getURI(), this.getClass().getClassLoader());
        } catch (IOException ex) {
            throw new RuntimeException("Missing configuration", ex);
        }
    }
}

and in Spring context:

<bean id="cacheManager" factory-bean="cacheManagerFactory" factory-method="getCacheManager" />

<bean id="cacheManagerFactory" class="com.test.CacheManagerFactory">
    <constructor-arg name="cachingProvider" ref="cachingManagerProvider" />
    <constructor-arg name="configurationLocation" value="/WEB-INF/ehcache.xml" />
</bean>

<bean id="cachingManagerProvider" class="org.ehcache.jsr107.EhcacheCachingProvider" />

The problem was specifying "/WEB-INF/ehcache.xml" as URI relative to webapp root as argument to org.ehcache.jsr107.EhcacheCachingProvider#getCacheManager() method.

Is it possible to inject without wrapper class?

0

There are 0 best solutions below