java - 用 @Cacheable 注释的方法不会被拦截

标签 java spring spring-cache

我是 Spring 缓存的新手。我在我的 maven pom 中使用 spring-boot-starter-1.4.0.RELEASE 。据我了解的文档,如果我采取这样的事情:

@Configuration
@EnableCaching
public class TestApplication {
    @Bean
    public CacheManager cacheManager() {
        // configure and return an implementation of Spring's CacheManager SPI
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("default")));
        return cacheManager;
    }

    @Bean
    public MyService myService() {
        // configure and return a class having @Cacheable methods
        return new MyService();
    }

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(TestConfiguration.class);
        MyService ms = ctx.getBean(MyService.class);
        ms.doCacheableOperation(); // calls the underlying method
        ms.doCacheableOperation(); // SHOULD just consult the cache
    }
}

并有一个这样的类:

public class MyService {
    @Cacheable
    public String doCacheableOperation() {
        System.out.println("======================CALLING EXPENSIVE METHOD=======================");
        return "done";
    }
}

当 main 方法在 TestApplication 中运行时,对 MyServce#doCacheableOperation 的第一次调用应该输出到屏幕,但第二次调用不应输出到屏幕,因为结果将从第一次开始被缓存。然而,事实并非如此。输出显示两次。

配置代码取自 EnableCaching 的 Javadoc:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/EnableCaching.html

让我困惑的一件事是,当我调试和检查 MyService 的实例时,它只是原始对象,没有包装在任何 CGLib 子类等中。

我需要如何更改配置/方法才能缓存 MyService#doCacheableOperation 的结果?

最佳答案

哦, child 。找到了。我发送到 SpringApplication#run 的类中有一个简单的拼写错误:

SpringApplication.run(TestConfiguration.class)

应该是

SpringApplication.run(TestApplication.class)

现在一切似乎都井然有序!

关于java - 用 @Cacheable 注释的方法不会被拦截,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39047139/

相关文章:

java - 缓存 : Why my diskStore path directory is not created?

java - 如何在 Java 中使用 for 循环生成 n 个具有不同变量名的实例

java - 如何防止 Element<Integer> 变成 Element<Object>

java - 如何在java中检查两个csv/xml文件是否相同

spring - 使用 gzip 压缩 rest 响应

java - 莫基托 : Calling real implementation

java - SHA 算法每次为相同的 key 生成唯一的哈希字符串

java - 什么时候值得在 Java 中使用 RegEx?

java - Spring @Cacheable 和 @Async 注解

java - spring-boot-devtools 在从缓存获取时导致 ClassCastException。