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

相关推荐
极小狐16 分钟前
从复制粘贴到可复用组件:极狐GitLab CI/CD 组件目录实战
java·ci/cd·gitlab·devops·组件化
编码者卢布16 分钟前
【Azure Function】NodeJS Function大批量写入到Redis遇见丢失数据情况的分析
redis·microsoft·azure
麻瓜code21 分钟前
【Agent】Spring AI RAG 实战:本地向量库 + 云端知识库
java·人工智能·spring
MC丶科29 分钟前
软考架构师90天冲刺|DAY44·Redis高级应用
数据库·数据仓库·redis·缓存·oracle·容器·规格说明书
小刘在重生~40 分钟前
Java 集合|Collection、List、ArrayList、LinkedList、泛型、Collections 工具类
java·数据结构·list
Boop_wu1 小时前
[redis] redis 快速入门
数据库·redis·github
我不会起名字3221 小时前
一天一道算法题(29):单调栈
java·数据结构·python·算法·leetcode·golang·单调栈
XR1234567881 小时前
医院移动医护零漫游无线网络选型指南
java·后端·struts
干到60岁退休的码农1 小时前
13.构建登录接口响应数据
java·spring boot·mybatis
三8441 小时前
Redis未授权访问与四种 getshell 路径(原理 → 实操,因果不断层)
redis·web安全·ssrf·getshell