代码之家  ›  专栏  ›  技术社区  ›  user1589188

在可缓存方法类cast异常中调用spring可缓存方法

  •  0
  • user1589188  · 技术社区  · 7 年前

    我正在尝试使用spring可缓存,但收到一个类转换异常

    @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线。我们知道为什么吗?

    1 回复  |  直到 7 年前
        1
  •  -1
  •   Stultuske    7 年前
    String e = service.getValue(name);
    

    看来 service.getValue(name); 返回的实例 Data ,不是字符串类型。

    你可能正在尝试的是:

    String e = service.getValue(name).getValue();
    

    但是你需要为 value 在你 数据 班级。

    不是这个,就是

    Data e = service.getValue(name);