Java 使用spring缓存缓存属性

Java 使用spring缓存缓存属性,java,spring,spring-mvc,collections,spring-cache,Java,Spring,Spring Mvc,Collections,Spring Cache,我正在尝试使用SpringCache实现对方法的缓存。问题是,在第一次之后,这个方法没有得到执行,这意味着属性没有得到加载。如果我删除@Cacheable注释,它可以正常工作。我的要求是,只要添加了新属性,该方法就应该运行并加载属性,否则它应该从缓存返回 @Cacheable("mycache") public Properties loadPropertyFile() throws Throwable { Properties properties = new Properties(

我正在尝试使用SpringCache实现对方法的缓存。问题是,在第一次之后,这个方法没有得到执行,这意味着属性没有得到加载。如果我删除@Cacheable注释,它可以正常工作。我的要求是,只要添加了新属性,该方法就应该运行并加载属性,否则它应该从缓存返回

 @Cacheable("mycache")
public Properties loadPropertyFile() throws Throwable {
    Properties properties = new Properties();
    try {
        logger.debug("Loading properties.");
        if (this.locations != null) {

            for (Resource location : this.locations) {
                if (logger.isInfoEnabled()) {
                    logger.info("Loading properties file from " + location);
                }
                try {
                    properties = PropertiesLoaderUtils.loadAllProperties(location.getFilename());

                } catch (IOException ex) {
                    if (this.ignoreResourceNotFound) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Could not load properties from "
                                    + location + ": " + ex.getMessage());
                        }
                    } else {
                        throw ex;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return properties;
}
XML文件:

 <cache:annotation-driven />


<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
  <set>
    <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="mycache" />
  </set>
</property>


代码工作正常:您配置可缓存的
注释的方式实际上永远不会失效,因为不存在触发逐出的条件。通常,您可以使用参数并向其传递SPeL表达式,但仍然无法检查基础文件是否已更改并有条件地执行方法体

这种“缓存直到更改”的实现无法工作,因为在实际重新加载文件(或检查其大小或时间戳,无论什么)之前,您都不知道是否添加了“新属性”

如果定期重新加载是一种可接受的选择,那么您可以尝试ApacheCommons配置,或者尝试Spring的配置