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

相关推荐
spencer_tseng9 分钟前
Tomcat Source Code Distributions
java·tomcat
烤麻辣烫15 分钟前
23种设计模式(新手)-5里氏替换原则
java·学习·设计模式·intellij-idea·里氏替换原则
喵手18 分钟前
网络编程:Java中的TCP与UDP通信!
java·udp·网络编程·tcp
u***13722 分钟前
【SpringBoot】【log】 自定义logback日志配置
java·spring boot·logback
小坏讲微服务37 分钟前
Spring Cloud Alibaba整合SkyWalking的监控完整使用
java·微服务·架构·springcloud·监控·skywalking·java微服务
chxii1 小时前
第六章:MySQL DQL 表之间的关系 自连接 一对一、一对多、多对一、多对多
java·前端·mysql
煎蛋学姐1 小时前
SSM基于J2EE的山西旅游网站的设计与实现iiqmx(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·java-ee·ssm 框架·山西旅游网站·在线预订系统
百***61871 小时前
Spring的构造注入
android·java·spring
小白宗轩1 小时前
vsCode的java配置
java·vscode·python
桦说编程1 小时前
如果让我从头再来学习并发编程
java·设计模式·性能优化