@Cachable 在没有输入参数的方法上?

mem*_*und 9 java spring caching spring-cache

我在@org.springframework.cache.annotation.Cachable注释方面遇到问题:

@Bean
public ConcurrentMapCache cache() {
    return new ConcurrentMapCache(CACHE);
}

@Cacheable(CACHE)
public String getApi() {
    return "api";
}

@Cacheable(CACHE)
public String getUrl() {
    return "url";
}
Run Code Online (Sandbox Code Playgroud)

用法:

assertEquals("api", service.getApi()); //OK
assertEquals("url", service.getUrl()); //FAILURE. this returns also "api"
Run Code Online (Sandbox Code Playgroud)

那么,如果方法签名不包含任何输入参数,为什么@Cachable 不通过方法名称创建缓存结果?

pvp*_*ran 11

尝试这个

@Cacheable(value = CACHE, key = "#root.method.name")
Run Code Online (Sandbox Code Playgroud)

您需要告诉 spring 使用方法名称作为键。您可以为此使用 SPEL。这是带有各种其他选项的文档

  • 虽然这有效 - 这不是违反直觉吗?我的意思是,为什么春天的家伙们曾经想过在没有参数的方法上添加 @Cachable 应该这样工作? (3认同)