使用@Cacheable注释的方法未被拦截

时间:2016-08-19 20:24:14

标签: 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";
    }
}

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

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

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

如何更改配置/方法以便缓存MyService#doCacheableOperation的结果?

1 个答案:

答案 0 :(得分:2)

哦,伙计。找到了。在我发送给SpringApplication#run:

的类中有一个简单的拼写错误
SpringApplication.run(TestConfiguration.class)

应该是

SpringApplication.run(TestApplication.class)

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