【发布时间】:2016-09-21 15:44:26
【问题描述】:
我试图在 spring boot 1.3.5 中使用 spring stater-cache,除了 @Configuration 类中的预加载缓存外一切正常。
Failed tests:
CacheTest.testCacheFromConfig: expected:<n[eal]> but was:<n[ot cached]>
请看下面的代码,如果你以前遇到过,请与我分享:)
@Component
public class CacheObject{
@CachePut(value = "nameCache", key = "#userId")
public String setName(long userId, String name) {
return name;
}
@Cacheable(value = "nameCache", key = "#userId")
public String getName(long userId) {
return "not cached";
}
}
@Component
public class CacheReference {
@Autowired
private CacheObject cacheObject;
public String getNameOut(long userId){
return cacheObject.getName(userId);
}
}
@Configuration
public class SystemConfig {
@Autowired
private CacheObject cacheObject;
@PostConstruct
public void init(){
System.out.println("------------------");
System.out.println("-- PRE LOAD CACHE BUT DIDN'T GET CACHED");
System.out.println("------------------");
cacheObject.setName(2, "neal");
cacheObject.setName(3, "dora");
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BootElastic.class)
@WebAppConfiguration
public class CacheTest {
@Autowired
private CacheObject cacheObject;
@Autowired
private CacheReference cacheReference;
@Test
public void testCache(){
String name = "this is neal for cache test";
long userId = 1;
cacheObject.setName(userId, name);
// cacheObject.setName(2, "neal"); // this will make test success
String nameFromCache = cacheReference.getNameOut(userId);
System.out.println("1" + nameFromCache);
Assert.assertEquals(nameFromCache, name);
}
@Test
public void testCacheFromConfig(){
String nameFromCache = cacheReference.getNameOut(2);
System.out.println("4" + nameFromCache);
Assert.assertEquals(nameFromCache, "neal");
}
}
【问题讨论】: