Spring @Cacheable not caching

夙愿已清 提交于 2019-12-06 03:31:31

Imagine you go to the Zoo. You go through the entrance once and pay your entry. Afterwards you can visit the Lions, the Tigers, and so on... You don't have to pay everytime because you did it when you entered. If you get bored and want to go to another Zoo, you have to go out, go to the next one, and pay again.

Your Class is the Zoo, your Methods are the Animals, and the Cache Proxy is the Entrance. When someone calls your class, it goes through the Cache once. When she is in, and calls another methods of the same class, it doesn't go through the Cache again. Only when you go out and in again, you go through the Cache.

There is a nasty trick you can use to override this called inject yourself:

public class YourClass {
    @Autowired
    private YourClass instance;

    @Cacheable
    public String method1() {
          // now you go through the cache again
          return instance.method2();
    }

    @Cacheable
    public String method2() {
          return "2";
    }
}

Ruben's answer is definitely correct, however I'll add something else that might be giving others trouble (like it did me). The annotation only seems to apply to public methods. It won't work on package protected even if it's in a different class.

Most funny reason for @Cacheable not to work is that you are "using"

springfox.documentation.annotations.Cacheable

instead of

org.springframework.cache.annotation.Cacheable

Note that this happens easily when you don't have the correct dependencies (yet) and your IDE does the import automatically..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!