2

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?

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
dsavickas
  • 1,360
  • 1
  • 9
  • 12
  • 2
    `WEB-INF` isn't the classpath. Just remove the `classpath:` prefix and it will load or move it to the classpath (i.e. in `src/main/resources`) to make it part of the classpath. – M. Deinum Sep 15 '20 at 08:18
  • @M.Deinum I face an issue with https://stackoverflow.com/questions/64868971/why-isnt-the-bean-found-spring-4-x-ehcache-3-x-apache-tomcat-7 – likejudo Nov 17 '20 at 03:35

0 Answers0