【问题标题】:Method annotated with @Cacheable not getting intercepted使用 @Cacheable 注释的方法没有被拦截
【发布时间】:2016-08-19 20:24:14
【问题描述】:

我是 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 的结果?

【问题讨论】:

    标签: java spring spring-cache


    【解决方案1】:

    哦,孩子。找到了。我发送给 SpringApplication#run 的课程中​​有一个简单的错字:

    SpringApplication.run(TestConfiguration.class)
    

    应该是

    SpringApplication.run(TestApplication.class)
    

    现在一切似乎都井井有条!

    【讨论】:

      猜你喜欢
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2020-03-29
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多