Spring Boot中@Cacheable注解未生效问题排查
问题描述(翻译后)
我正在使用Java 17搭配Spring Boot 2.7.2开发项目。我有一个标注了@Component的ClientImpl类,它实现了Client接口,其中包含一个返回ReportType[]的publicReports()方法,原本运行正常。
@Component public class ClientImpl implements Client { @Override public ReportType[] publicReports {...} }
对应的RestController代码如下:
@RestController @RequestMapping("/rest") public class RestService { @Autowired private Client client; ... @GetMapping( path = "reportTypes", produces = MediaType.APPLICATION_JSON) @RolesAllowed("ROLE_AGNI_BDAC") public ResponseEntity<ReportType[]> getPublicReportTypes( @RequestParam(required = false, defaultValue = "ca") String language) { return ResponseEntity.ok().body(client.publicReports()); } }
由于该方法会调用外部WS获取类型主列表,我希望对其调用进行缓存。因此我在pom.xml中添加了以下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
并修改了ClientImpl类:
@Component public class ClientImpl implements Client { @Override @Cacheable("publicReportTypes") public ReportType[] publicReports {...} }
但完成上述操作后,我多次调用该接口,每次都能看到日志显示publicReports()方法正在执行。请问我遗漏了什么配置?
更新:我的@SpringBootApplication类代码如下:
@SpringBootApplication public class BdacServiceApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(BdacServiceApplication.class, args); } @Override public void run(String... args) throws Exception { } }
解决方案
核心问题:未启用Spring缓存机制
Spring Boot的缓存注解(如@Cacheable)需要通过@EnableCaching注解激活缓存代理逻辑,你当前的启动类缺少该注解,导致缓存功能完全未生效。
修复步骤
在你的BdacServiceApplication启动类上添加@EnableCaching注解:
@SpringBootApplication @EnableCaching // 新增此注解开启缓存功能 public class BdacServiceApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(BdacServiceApplication.class, args); } @Override public void run(String... args) throws Exception { } }
额外排查项(若修复后仍不生效)
- 代理调用验证:确保是通过接口实例调用
publicReports()方法(你当前Controller注入的是Client接口,符合要求),如果是类内部自调用会绕过代理,导致缓存失效。 - 缓存键确认:由于
publicReports()无参数,默认缓存键是固定的,不会出现参数不同导致缓存不命中的情况;若后续方法添加参数,可通过@Cacheable的key属性自定义键规则。 - 缓存管理器初始化:Spring Boot会自动配置默认缓存管理器(如
ConcurrentMapCacheManager),可通过开启org.springframework.cache包的DEBUG日志,确认缓存管理器是否正常初始化。
添加@EnableCaching后,首次调用接口会执行publicReports()并缓存结果,后续请求将直接返回缓存数据,不再执行方法体。
内容的提问来源于stack exchange,提问作者SJuan76
相关产品推荐
相关产品推荐

