Issue
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
Solution
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");
}
}
Answered By - Carlos López Marí
Answer Checked By - Robin (JavaFixing Admin)