英文:
Spring's @Cacheable not working when called from the controller in Spring Boot
问题
你是否了解针对这种情况的Spring Boot特定解决方案?
我按照步骤实现了Spring的@Cacheable
,但尽管我将代码简化为最简单的示例,它对我不起作用:
@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");
}
}
对localhost:8080/test
的每个请求都会打印这个字符串,不仅仅是第一个请求。
我已在我的主类上加上了@EnableCaching
注解。
英文:
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
答案1
得分: 2
就像安德鲁所说,正确的问题应该是“在相同 类 中调用时”。
但是,由于建议帖子的回答过时了,并且有更好的方法适用于更新版本的Spring,我想分享我认为是最佳方法的做法:
- 自动装配控制器并使用它来调用方法,而不是使用类上下文的
this
。
更新后的代码将如下所示:
@Controller
public class TestController {
@Autowired TestController self;
@RequestMapping("/test")
public String testView(){
self.expensiveMethod();
return "test";
}
@Cacheable("ones")
public void expensiveMethod(){
System.out.println("现在正在使用缓存");
}
}
英文:
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");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论