首页 > 解决方案 > 通过 XML 配置 Spring Ehcache 3.x

问题描述

我正在尝试javax.cache.CacheManager使用 Spring XML 上下文注入 Ehcache (v3.9) (JSR-107 JCache API)。初步尝试:

<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" />

失败了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

我设法只使用适配器类来做到这一点:

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);
        }
    }
}

在 Spring 上下文中:

<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" />

问题是将“/WEB-INF/ehcache.xml”指定为相对于 webapp root 作为org.ehcache.jsr107.EhcacheCachingProvider#getCacheManager()方法参数的 URI。

是否可以在没有包装类的情况下注入?

标签: javaspringehcachejcache

解决方案


推荐阅读