Spring Cacheable不起作用

时间:2014-11-02 12:27:39

标签: java spring caching

我使用Spring配置

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <mvc:annotation-driven />
    <mvc:resources mapping="/static/**" location="/static/" />

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

<bean id="bucketsGenerator" class="net.rwchess.utils.PythonBucketsGenerationService">
        <constructor-arg index="0" value="/home/bodia/server/jetty/webapps/ROOT/WEB-INF/python/"/>
    </bean>
..........

 <mvc:default-servlet-handler />    
</beans>

并且generateBuckets()中的方法PythonBucketsGenerationService可以缓存返回值。所以我宣布:

@Service
public class PythonBucketsGenerationService {

    private String pythonDir;

    public PythonBucketsGenerationService(String pythonDir) {
        this.pythonDir = pythonDir;
    }

    @Cacheable(value = "buckets")
    public List<Bucket> generateBuckets(List<TournamentPlayer> players) {
    .....
    }
}

问题是即使List<TournamentPlayer> players的hashCode具有相同的值(我已检查),该方法也会在每次调用时执行。 TournamentPlayer已正确覆盖equals()hashCode()。这有什么不对?

1 个答案:

答案 0 :(得分:3)

您很可能缺少启用注释驱动的缓存配置(缓存:注释驱动)。见这个例子:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

    <cache:annotation-driven />

</beans>

转到此页面以获取更多文档:http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/cache.html