You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中使用REST时@Cacheable注解不生效问题排查

@Cacheable注解未生效的原因及解决办法

核心问题:手动实例化Bean导致缓存代理失效

你在EventController里直接通过new EventRepository()创建实例,而非依赖Spring容器注入。Spring的@Cacheable是基于AOP动态代理实现的,只有Spring容器管理的Bean才会被生成代理对象,进而触发缓存逻辑。手动new的对象不在Spring管理范围内,自然不会应用缓存切面。

解决步骤

1. 改用Spring依赖注入获取EventRepository

把手动实例化代码替换为Spring注入方式:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;

@RestController
public class EventController {
    
    @Autowired
    private EventRepository eventRepository;
    
    @GetMapping(value = "events/{eventId}")
    public String getEvent(@PathVariable Integer eventId) throws InterruptedException {
        return this.eventRepository.getEvent(eventId);
    }
}

2. 推荐:使用构造函数注入

Spring官方更推荐构造函数注入,可避免空指针问题,同时提升代码可测试性:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EventController {
    
    private final EventRepository eventRepository;

    public EventController(EventRepository eventRepository) {
        this.eventRepository = eventRepository;
    }
    
    @GetMapping(value = "events/{eventId}")
    public String getEvent(@PathVariable Integer eventId) throws InterruptedException {
        return this.eventRepository.getEvent(eventId);
    }
}

额外验证点

  • 你已经在启动类TestTestApplication上正确标注@EnableCaching,这部分无需修改
  • EventRepository上的@Component注解正常生效,Spring能扫描到该Bean,这部分也没问题

修改后,首次请求会等待5秒,后续相同eventId的请求会直接返回缓存结果,不再执行休眠逻辑。

内容的提问来源于stack exchange,提问作者ilhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 14:22:08