1

Do you know a Spring Boot specific soltution to this scenario?

I followed the steps to implement Spting's @Cacheable but it is not working for me although I reduced the code to the simplest example:

@Controller
public class TestController {

    @RequestMapping("/test")
    public String testView(){
        expensiveMethod();
        return "test";
    }


    @Cacheable("ones")
    public void expensiveMethod(){
       System.out.println("Cache is not being used");
    }

}

Every request to localhost:8080/test prints the string, not just the first one.

I annotated my main class with @EnableCaching

Carlos López Marí
  • 1,432
  • 3
  • 18
  • 45
  • 2
    Looks to be the same as [this other question](https://stackoverflow.com/questions/12115996/spring-cache-cacheable-method-ignored-when-called-from-within-the-same-class). – Andrew S Sep 18 '20 at 14:57
  • That question and its answers are really outdated and doesn't have in count the autowiring properties of Spring Boot. This question is really clear about the best way to do it with the new archetype. – Carlos López Marí Nov 26 '20 at 11:36

1 Answers1

2

Like Andrew said, the right question should be "when called in the same class".

But as the answers to the suggested post are really outdated and there are better approaches that are useful with newer versions of Spring, i would like to share what I think is the best approach:

  • Autowire the controller and use to call the method it instead of using the class context this.

The updated code would look like:

@Controller
public class TestController {


    @Autowired TestController self;

    @RequestMapping("/test")
    public String testView(){
        self.expensiveMethod();
        return "test";
    }


    @Cacheable("ones")
    public void expensiveMethod(){
       System.out.println("Cache is now being used");
    }

}
Carlos López Marí
  • 1,432
  • 3
  • 18
  • 45