spring – 使用谷歌番石榴缓存

我试图在我的春季应用程序中使用谷歌番石榴缓存,但结果永远不会缓存。

这是我的步骤:

在conf文件中:

@EnableCaching @Configuration public class myConfiguration { @Bean(name = "CacheManager") public CacheManager cacheManager() { return new GuavaCacheManager("MyCache"); } } 

在课堂上我想使用缓存:

 public class MyClass extends MyBaseClass { @Cacheable(value = "MyCache") public Integer get(String key) { System.out.println("cache not working"); return 1; } } 

然后当我打电话时:

 MyClass m = new MyClass(); m.get("testKey"); m.get("testKey"); m.get("testKey"); 

它每次都进入function而不使用缓存:console:

  cache not working cache not working cache not working 

有人知道我错过了什么或者我该如何调试?

你不应该自己管理一个春豆。 让spring来管理它。

 @EnableCaching @Configuration public class myConfiguration { @Bean(name = "CacheManager") public CacheManager cacheManager() { return new GuavaCacheManager("MyCache"); } @Bean public MyClass myClass(){ return new MyClass(); } } 

之后,您应该以托管方式使用MyClass。

 public static void main(String[] args) throws Exception { final ApplicationContext applicationContext = new AnnotationConfigApplicationContext(myConfiguration.class); final MyClass myclass = applicationContext.getBean("myClass"); myclass.get("testKey"); myclass.get("testKey"); myclass.get("testKey"); }