@Cacheable [Spring MVC]无法正常工作

时间:2018-05-02 10:23:06

标签: java spring spring-mvc spring-annotations spring-cache

我的春季项目有一个罐子包装。我使用的是Spring 4.3.2 在我的资源文件夹中。我有一个基于xml的配置文件:abc-servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:mvc="http://www.springframework.org/schema/mvc"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:beans="http://www.springframework.org/schema/beans"
         xmlns:cache="http://www.springframework.org/schema/cache"
         xmlns:p="http://www.springframework.org/schema/p"
         xmlns:context="http://www.springframework.org/schema/context"
         xsi:schemaLocation="http://www.springframework.org/schema/mvc
                    http://www.springframework.org/schema/mvc/spring-mvc.xsd
                    http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context.xsd
                    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

<cache:annotation-driven />

<context:component-scan base-package="sayak.auth,
                        sayak.member"/>

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

我在如下所示的dao方法上使用@Cacheable,并使用@Component注释该类:

@Cacheable(value="memberInLastMonth" , key="#authenticationId")
public List<AuthenticationAuditTrail> findByAuthenticationId(long authenticationId) {
//DB call to fetch data
}

当在同一个authenticationId上调用时,此方法的结果不会被缓存,我使用了一个简单的断言来检查它而没有获得所需的结果。任何领导都会有所帮助。

测试方法:

@Test
public void testMemberInLastMonth() {
Member member=getMember();
List<AuthenticationAuditTrail> records = getDAO()
    .findByAuthenticationId(member.getAuthentication().getId(),
        DateUtil.getPastMonth(1));
List<AuthenticationAuditTrail> cachedRecords = getDAO()
    .findByAuthenticationId(member.getAuthentication().getId(),
        DateUtil.getPastMonth(1));

for(int i=0;i<records.size();i++){
  AssertUtil.assertTrue(records.get(0) == cachedRecords.get(0));
}

}

0 个答案:

没有答案