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四大核心组件,你知道几个? - 知乎

相关推荐
字节源流3 小时前
关于maven的依赖下不下来的问题
java·maven
pjx9873 小时前
服务间的“握手”:OpenFeign声明式调用与客户端负载均衡
java·运维·spring·负载均衡
jjkkzzzz3 小时前
Linux下的c/c++开发之操作Redis数据库
数据库·c++·redis
prinrf('千寻)4 小时前
MyBatis-Plus 的 updateById 方法不更新 null 值属性的问题
java·开发语言·mybatis
老华带你飞4 小时前
实习记录小程序|基于SSM+Vue的实习记录小程序设计与实现(源码+数据库+文档)
java·数据库·spring boot·小程序·论文·毕设·实习记录小程序
在未来等你4 小时前
互联网大厂Java求职面试:AI与大模型应用集成及云原生挑战
java·微服务·ai·kubernetes·大模型·embedding·spring ai
my_styles5 小时前
docker-compose部署项目(springboot服务)以及基础环境(mysql、redis等)ruoyi-ry
spring boot·redis·后端·mysql·spring cloud·docker·容器
源码技术栈5 小时前
SaaS基于云计算、大数据的Java云HIS平台信息化系统源码
java·大数据·云计算·云his·his系统·云医院·区域his
编程、小哥哥5 小时前
互联网大厂Java面试:从Spring Boot到微服务架构的技术深挖
java·spring boot·redis·微服务·prometheus·面试技巧