SpringBoot 注入RedisTemplat 启动报错

需求

因为需要限制部门内多个人员同一时间操作同一批客户的需求,考虑下决定用Redis滑动窗口实现自过期以及并发校验。

问题

新建了个Redis工具类封装RedisTemplat 操作,到启动时却发现无法正常启动,报错注入错误。

The injection point has the following annotations:

  • @org.springframework.beans.factory.annotation.Autowired(required=true)

The following candidates were found but could not be injected:

  • Bean method 'redisTemplate' in 'RedisAutoConfiguration' not loaded because @ConditionalOnMissingBean (names: redisTemplate; SearchStrategy: all) found beans named redisTemplate

然后发现SpringBoot autoConfigure 中的RedisAutoConfiguration类已经注入了名为redisTemplate,类型为RedisTemplate<Object, Object>的JavaBean。使用@AutoWired 注解 byType(根据Bean的类型)自动装配,无法找到对应的Bean。

解决

后续,使用@Resource byName装配即可正常使用;或者RedisTemplate不指定泛型使用。

总结

之前背八股,经常说到@AutoWire与@Resource的区别,baType byName blahblah,但是真正去用、理解还是之上谈兵。

spring-boot-autoconfigure 模块

autoconfigure内容是配置Bean实例到Spring容器的实际代码实现包,然后提供给starter依赖。Spring Boot Starter帮我们自动注入了需要的Bean实例到Spring 容器中,不需要我们手动配置,SpringBoot 通过 spring-boot-autoconfigure 也体现了 "约定优于配置" 这一设计原则。

SpringBoot 则可以依据 classpath 里面的依赖内容来自动配置 Bean 到 IOC 容器,Auto-configuration 会尝试推断哪些 Beans 是用户可能会需要的。比如如果HSQLDB 包在当前 classpath 下,并且用户并没有配置其他数据库链接,这时候 Auto-configuration 功能会自动注入一个基于内存的数据库连接到应用的 IOC 容器。但是要开启这个自动配置功能需要添加 @EnableAutoConfiguration 注解。

toLearn: SpringBoot核心组件,autoconfigure的实现

参考:

SpringBoot:模块探究之spring-boot-autoconfigure-CSDN博客

SpringBoot四大核心组件,你知道几个? - 知乎

相关推荐
头发还在的女程序员1 小时前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
Cosolar3 小时前
从 Java 21 升到 25、Spring Boot 3 升 4:一次可复现的迁移踩坑实录
java·后端·面试
Joy T5 小时前
Spring Security 从 Acegi 到 AI Agent——JWT、角色鉴权与异步任务安全实战
人工智能·安全·spring·spring security·json web token·securitycontext·多次鉴权
IT空门:门主5 小时前
LangChain4j 1.24.0 深度解读:新特性、版本对比与学习路线
java·学习
Flynn Liang6 小时前
全栈实战:从零搭建一套可落地的生产级 AI 智能体系统(Redis 版)
人工智能·redis·ai agent
用户3721574261357 小时前
Java 批量操作 Excel 超链接:添加、读取、修改和删除
java
 梦晓天明7 小时前
1.Spring学习笔记_IOC入门案例
笔记·学习·spring
用户3721574261358 小时前
Java 将 Excel 图表导出为图片:指定图表、批量导出与图表工作表
java
这个昵称不容易9 小时前
交流论坛网站设计与实现:SpringBoot 论坛 130 个接口,附论文与运行截图
java·springboot·毕设
船神丿男人9 小时前
DevDocQA 的 Redis 答案缓存实战:版本切换、异步写回与故障排查
数据库·redis·缓存