3

I'm trying to use google guava cache in my spring app, but result is never caching.

This are my steps:

in conf file:

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

In class I want to use caching:

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

Then when I'm calling:

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

It's entering function each time and not using cache: console:

 cache not working
 cache not working 
 cache not working

Does someone have an idea what am I missing or how can I debug that?

griffon vulture
  • 6,594
  • 6
  • 36
  • 57
  • Have you added a CacheBuilder into your spring config? – Les Aug 19 '15 at 10:41
  • And why should it work? You are creating a new instance of the class yourself, whereas you should a spring configured (and thus proxied) instance for caching to work. – M. Deinum Aug 19 '15 at 10:50
  • @m. Deinum Can you explain? what do you mean spring configured instance? – griffon vulture Aug 19 '15 at 10:53
  • Spring uses AOP to apply caching, however you are using your own instance of `MyClass` which isn't being proxied by spring. Regardless how much configuration you are going to throw at it, it will not work. Configure the `MyClass` as a spring bean, get an/the instance from the context and use that instead of your own instance – M. Deinum Aug 19 '15 at 10:56

1 Answers1

2

You should not manage a spring bean by yourself. Let spring to manage it.

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

        @Bean
        public MyClass myClass(){
            return new MyClass();
        }
}

After that you should use MyClass in a managed manner.

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");
}
bhdrkn
  • 6,244
  • 5
  • 35
  • 42