Spring缓存配置遇到的坑

基本配置

    <cache:annotation-driven cache-manager="cacheManager"/>  


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

遇到的问题:

1. 没有缓存,每一次都是跑进方法里面。

我怀疑是不是@Cacheable没有被扫描得到?

后来我就在xml里手动写了一个配置<bean id="testdd" class="cn.angelshelter.fm2017.service.TestCacheService"></bean>,后来发现能认别了。666

因为我的项目有两个配置文件,一个是springmvc-servlet.xml,另一个是applicationContext.xml,

springmvc-servlet.xml里面有 <context:component-scan base-package="cn.angelshelter" />,而applicationContext.xml里面没有 <context:component-scan base-package="cn.angelshelter" />,好像就是这个原因,所以applicationContext.xml里面都不会自己去扫描。

后来,我把文章开头提到的两段配置移到springmvc-servlet.xml就可以正常扫描了。

后为,我发现,其实只有把<cache:annotation-driven cache-manager="cacheManager"/> 移到springmvc-servlet.xml,另一部分保留在applicationContext.xml也是可以自动扫描到的。

这个可能是可spring配置文件的作用域有关吧,我反正不太懂。

2. 与元素类型 "bean" 相关联的属性 "p:name" 的前缀 "p" 未绑定。

不支持前辍p:, 加上 xmlns:p="http://www.springframework.org/schema/p" 就好了。

或者你就不使用p:格式,把<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"/>换成

 <bean name="default" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" />也可以。

3. 缓存配置@Cacheable(value="books")中的value的值,一定是要存在的,就是放在<bean id="cacheManager">的caches属性set集合中有定义,比如上面定义的default和books

今天试了一下ehcache的集群(分布式)配置(RMI方式),2017-03-16

这个家伙讲得很具体,我就不多赘言了,直接上链接http://www.tuicool.com/articles/MJzYZbR

原文地址:https://www.cnblogs.com/angelshelter/p/6543150.html