【发布时间】:2019-05-08 01:39:06
【问题描述】:
我正在尝试使用 Spring Cacheable,但遇到类转换异常
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CacheableTest.class, loader = AnnotationConfigContextLoader.class)
@Configuration
@EnableCaching
public class CacheableTest {
public static final String CACHE = "cache";
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager(CACHE);
}
@Autowired
DataService service;
@Test
public void cacheTest() {
final String name = "name";
Data a = service.getData(name);
Data b = service.getData(new String(name));
Assert.assertSame(a, b);
String c = service.getValue(service.getData(name));
String d = service.getValue(service.getData(new String(name)));
Assert.assertSame(c, d);
String e = service.getValue(name);
String f = service.getValue(new String(name));
Assert.assertSame(e, f);
}
public static class Data {
private String value;
public Data(String value) {
this.value = value;
}
}
@Service
public static class DataService {
@Resource
private DataService self;
@Cacheable(CACHE)
public Data getData(String name) {
return new Data(name);
}
@Cacheable(CACHE)
public String getValue(Data data) {
return data.value;
}
@Cacheable(CACHE)
public String getValue(String name) {
return self.getData(name).value;
}
}
}
异常说 CacheableTest$Data cannot be cast to java.lang.String 发生在字符串 e 行。我们知道为什么吗?
【问题讨论】:
标签: java spring spring-cache