Bean named ‘redisTemplate‘ is expected to be of type ‘org.springframework.data.redis.core.StringRedi

本文讲述了@Autowired和@Resource注解在Spring框架中的区别,以及在使用RedisTemplate时遇到的依赖注入错误,提供了通过@Repository或改变注解方式来解决问题的方法。

本文将讲解:

  1. 该错误的解决办法
  2. @Resource@Autowired 两个注解的区别
  3. @Autowired这个注解注入的字段爆红

今天在引入redis作为缓存中间件的时候,出现了这个错误,org.springframework.beans.factory.UnsatisfiedDependencyException,其实就是我们自动注入的时候报的错误,使用@Resouce这个注解,因为这个注解我们是先通过名字去匹配的,然后再通过type去匹配的

报错详细信息:

Bean named 'redisTemplate' is expected to be of type 'org.springframework.data.redis.core.StringRedisTemplate' but was actually of type 'org.springframework.data.redis.core.RedisTemplate'
名为“redisTemplate”的Bean应该属于“org.springframework.data.redis.core.StringRedisTemplate”类型,但实际上是“org.springframework.data.redis.core.RedisTemplate”类型。

出现这个问题的就是,我们在自动装配的时候没有找到该名字的bean,然后通过类型查找也没有查询到

解决方案:

1.改为@Autowired注入
@Autowired
StringRedisTemplate redisTemplate;
2.改为字段名
@Resource
StringRedisTemplate stringRedisTemplate;

今天就在这里浅谈一下 @Resource@Autowired 两个注解的区别

@Autowired

  • 这个注解是spring提供的
  • 按照type查找bean,他是在spring容器中去查找有没有这个type的bean
  • 如果我们使用@Qualifier注解声明了name,则从结果集中取出与该name相匹配的bean返回(此时可以视为通过name和type获取bean,但实质是先通过type获取所有bean,然后通过name筛选
  • 如果没有使用@Qualifier注解,且找到多个bean,则判断这些bean中是否有使用@Primary注解和@Priority注解,有就返回优先级最高的哪一个bean,没有就按照字段名称去匹配bean,匹配成功返回,不成功抛出异常。

如果还需要详细的了解,可以去查看一下源码 findAutowireCandidates()和determineAutowireCandidate()这个两个方法的源码

@Resource

  • 这个注解是由jdk提供的
  • 按照name属性查找,如果我们没有指定name属性,则会把name属性值处理为字段名
  • 先按照name属性值注入,若未找到,则按照type属性值注入

@Autowired注入字段爆红

场景描述:
场景描述


原因分析:

因为这个注解是spring提供的注解,他会按照type去spring容器中查找这个bean,如果这里爆红的话,那就是没有头把这个注入到spring容器中,找不到这个bean

原因分析

解决办法一:

在需要使用@Autowired注入的类上添加@Repository注解即可,这个注解是Spring的注解,作用是把当前类注册到Srping容器中实例化为一个bean,这样的话@Autowired就可以找到这个bean了
这里如果是我们的工具类的话,建议使用 @Component这个注解
因为上面那个注解主要用于dao层,用来确定类的标识作用(约定)

解决办法二:

将@Autowired注解替换成@Resource注解,该注解是JDK内部的注解,不会向@Autowired那样去Spring容器中寻找bean。
使用@Resource我们需要注意名字不能写错或者少写

解决结果

这边文章就浅谈到这里,写的不好的地方大家多多担待指正,谢谢大家

C:\Users\lijw0\.jdks\corretto-1.8.0_442\bin\java.exe -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:45918,suspend=y,server=n -javaagent:C:\Users\lijw0\AppData\Local\JetBrains\IntelliJIdea2025.1\captureAgent\debugger-agent.jar=file:///C:/Users/lijw0/AppData/Local/Temp/capture4886985102263896140.props -agentpath:C:\Users\lijw0\AppData\Local\Temp\idea_libasyncProfiler_dll_temp_folder1\libasyncProfiler.dll=version,jfr,event=wall,interval=10ms,cstack=no,file=C:\Users\lijw0\IdeaSnapshots\sdsEHSApplication_2025_11_06_103420.jfr,dbghelppath=C:\Users\lijw0\AppData\Local\Temp\idea_dbghelp_dll_temp_folder\dbghelp.dll,log=C:\Users\lijw0\AppData\Local\Temp\sdsEHSApplication_2025_11_06_103420.jfr.log.txt,logLevel=DEBUG -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-Dmanagement.endpoints.jmx.exposure.include=*" -Dkotlinx.coroutines.debug.enable.creation.stack.trace=false -Ddebugger.agent.enable.coroutines=true -Dkotlinx.coroutines.debug.enable.flows.stack.trace=true -Dkotlinx.coroutines.debug.enable.mutable.state.flows.stack.trace=true -Dfile.encoding=UTF-8 -classpath "D:\JavaSoftWare\IntelliJ IDEA 2025.1\lib\idea_rt.jar" com.intellij.rt.execution.CommandLineWrapper C:\Users\lijw0\AppData\Local\Temp\idea_classpath846579415 com.sdsEHS.sdsEHSApplication Connected to the target VM, address: '127.0.0.1:45918', transport: 'socket' . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.5.14) 10:34:24.321 [background-preinit] INFO o.h.v.i.util.Version - [<clinit>,21] - HV000001: Hibernate Validator 6.2.3.Final 10:34:24.326 [main] INFO c.s.sdsEHSApplication - [logStarting,55] - Starting sdsEHSApplication using Java 1.8.0_442 on DESKTOP-83AD4BH with PID 22380 (D:\SHProjects\sds_ehs\admin\target\classes started by lijw0 in D:\SHProjects\sds_ehs) 10:34:24.327 [main] DEBUG c.s.sdsEHSApplication - [logStarting,56] - Running with Spring Boot v2.5.14, Spring v5.3.20 10:34:24.327 [main] INFO c.s.sdsEHSApplication - [logStartupProfileInfo,686] - The following 1 profile is active: "test" 10:34:27.233 [main] WARN o.m.s.m.ClassPathMapperScanner - [warn,44] - Skipping MapperFactoryBean with name 'inComingMapper' and 'com.sdsEHS.restful.mapper.InComingMapper' mapperInterface. Bean already defined with the same name! 10:34:27.233 [main] WARN o.m.s.m.ClassPathMapperScanner - [warn,44] - Skipping MapperFactoryBean with name 'outComingMapper' and 'com.sdsEHS.restful.mapper.OutComingMapper' mapperInterface. Bean already defined with the same name! 10:34:27.234 [main] WARN o.m.s.m.ClassPathMapperScanner - [warn,44] - Skipping MapperFactoryBean with name 'testResultMapper' and 'com.sdsEHS.restful.mapper.TestResultMapper' mapperInterface. Bean already defined with the same name! 10:34:27.234 [main] WARN o.m.s.m.ClassPathMapperScanner - [warn,44] - Skipping MapperFactoryBean with name 'checkItemMapper' and 'com.sdsEHS.environmental.mapper.CheckItemMapper' mapperInterface. Bean already defined with the same name! 10:34:27.234 [main] WARN o.m.s.m.ClassPathMapperScanner - [warn,44] - Skipping MapperFactoryBean with name 'checkOrderMapper' and 'com.sdsEHS.environmental.mapper.CheckOrderMapper' mapperInterface. Bean already defined with the same name! 10:34:27.235 [main] WARN o.m.s.m.ClassPathMapperScanner - [warn,44] - Skipping MapperFactoryBean with name 'deviceAllMapper' and 'com.sdsEHS.environmental.mapper.DeviceAllMapper' mapperInterface. Bean already defined with the same name! 10:34:27.235 [main] WARN o.m.s.m.ClassPathMapperScanner - [warn,44] - Skipping MapperFactoryBean with name 'deviceMapper' and 'com.sdsEHS.environmental.mapper.DeviceMapper' mapperInterface. Bean already defined with the same name! 10:34:27.235 [main] WARN o.m.s.m.ClassPathMapperScanner - [warn,44] - Skipping MapperFactoryBean with name 'safetyHazardReviewRecordMapper' and 'com.sdsEHS.hazardManagement.mapper.SafetyHazardReviewRecordMapper' mapperInterface. Bean already defined with the same name! 10:34:28.925 [main] INFO o.a.c.h.Http11NioProtocol - [log,173] - Initializing ProtocolHandler ["http-nio-8000"] 10:34:28.926 [main] INFO o.a.c.c.StandardService - [log,173] - Starting service [Tomcat] 10:34:28.926 [main] INFO o.a.c.c.StandardEngine - [log,173] - Starting Servlet engine: [Apache Tomcat/9.0.63] 10:34:29.291 [main] INFO o.a.c.c.C.[.[.[/] - [log,173] - Initializing Spring embedded WebApplicationContext 10:34:30.359 [main] INFO org.redisson.Version - [logVersion,41] - Redisson 3.16.4 10:34:32.344 [redisson-netty-2-17] INFO o.r.c.p.MasterPubSubConnectionPool - [lambda$run$0,166] - 1 connections initialized for 127.0.0.1/127.0.0.1:6379 10:34:32.366 [redisson-netty-2-19] INFO o.r.c.p.MasterConnectionPool - [lambda$run$0,166] - 24 connections initialized for 127.0.0.1/127.0.0.1:6379 10:35:01.914 [main] INFO c.a.d.p.DruidDataSource - [init,972] - {dataSource-1} inited 10:35:01.977 [main] DEBUG c.s.s.m.S.selectConfigList - [debug,137] - ==> Preparing: select config_id, config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark from sys_config 10:35:02.123 [main] DEBUG c.s.s.m.S.selectConfigList - [debug,137] - ==> Parameters: 10:35:02.271 [main] DEBUG c.s.s.m.S.selectConfigList - [debug,137] - <== Total: 5 10:35:03.519 [main] DEBUG c.s.f.s.f.JwtAuthenticationTokenFilter - [init,242] - Filter 'jwtAuthenticationTokenFilter' configured for use 10:35:04.364 [main] DEBUG c.s.s.m.S.selectDictDataList - [debug,137] - ==> Preparing: select dict_code, dict_sort, dict_label, dict_value, dict_type, css_class, list_class, is_default, status, create_by, create_time, remark from sys_dict_data WHERE status = ? order by dict_sort asc 10:35:04.406 [main] DEBUG c.s.s.m.S.selectDictDataList - [debug,137] - ==> Parameters: 0(String) 10:35:04.518 [main] DEBUG c.s.s.m.S.selectDictDataList - [debug,137] - <== Total: 67 10:35:05.558 [main] INFO o.q.i.StdSchedulerFactory - [instantiate,1220] - Using default implementation for ThreadExecutor 10:35:05.628 [main] INFO o.q.c.SchedulerSignalerImpl - [<init>,61] - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl 10:35:05.628 [main] INFO o.q.c.QuartzScheduler - [<init>,229] - Quartz Scheduler v.2.3.2 created. 10:35:05.641 [main] INFO o.q.s.RAMJobStore - [initialize,155] - RAMJobStore initialized. 10:35:05.645 [main] INFO o.q.c.QuartzScheduler - [initialize,294] - Scheduler meta-data: Quartz Scheduler (v2.3.2) 'quartzScheduler' with instanceId 'NON_CLUSTERED' Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally. NOT STARTED. Currently in standby mode. Number of jobs executed: 0 Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads. Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered. 10:35:05.645 [main] INFO o.q.i.StdSchedulerFactory - [instantiate,1374] - Quartz scheduler 'quartzScheduler' initialized from an externally provided properties instance. 10:35:05.645 [main] INFO o.q.i.StdSchedulerFactory - [instantiate,1378] - Quartz scheduler version: 2.3.2 10:35:05.645 [main] INFO o.q.c.QuartzScheduler - [setJobFactory,2293] - JobFactory set to: org.springframework.scheduling.quartz.SpringBeanJobFactory@1e3a2177 10:35:05.703 [main] DEBUG c.s.q.m.S.selectJobAll - [debug,137] - ==> Preparing: select job_id, job_name, job_group, invoke_target, cron_expression, misfire_policy, concurrent, status, create_by, create_time, remark from sys_job 10:35:05.704 [main] DEBUG c.s.q.m.S.selectJobAll - [debug,137] - ==> Parameters: 10:35:05.736 [main] DEBUG c.s.q.m.S.selectJobAll - [debug,137] - <== Total: 5 10:35:06.158 [main] WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - [refresh,591] - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'safetyHazardReviewRecordController': Unsatisfied dependency expressed through field 'safetyHazardReviewRecordService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'safetyHazardReviewRecordServiceImpl': Unsatisfied dependency expressed through field 'redisPlanNumberGenerator'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisPlanNumberGenerator' defined in file [D:\SHProjects\sds_ehs\HazardManagement\target\classes\com\sdsEHS\hazardManagement\util\RedisPlanNumberGenerator.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} 10:35:06.158 [main] INFO o.q.c.QuartzScheduler - [shutdown,666] - Scheduler quartzScheduler_$_NON_CLUSTERED shutting down. 10:35:06.159 [main] INFO o.q.c.QuartzScheduler - [standby,585] - Scheduler quartzScheduler_$_NON_CLUSTERED paused. 10:35:06.159 [main] INFO o.q.c.QuartzScheduler - [shutdown,740] - Scheduler quartzScheduler_$_NON_CLUSTERED shutdown complete. 10:35:06.160 [main] INFO sys-user - [shutdownAsyncManager,31] - ====关闭后台任务任务线程池==== 10:35:06.168 [main] WARN o.s.c.a.CommonAnnotationBeanPostProcessor - [postProcessBeforeDestruction,185] - Destroy method on bean with name 'shutdownManager' threw an exception: java.lang.ExceptionInInitializerError 10:35:06.173 [main] INFO c.a.d.p.DruidDataSource - [close,2051] - {dataSource-0} closing ... 10:35:06.174 [main] INFO c.a.d.p.DruidDataSource - [close,2051] - {dataSource-1} closing ... 10:35:06.186 [main] INFO c.a.d.p.DruidDataSource - [close,2124] - {dataSource-1} closed 10:35:06.247 [main] INFO o.a.c.c.StandardService - [log,173] - Stopping service [Tomcat] 10:35:06.252 [main] WARN o.a.c.l.WebappClassLoaderBase - [log,173] - The web application [ROOT] appears to have started a thread named [Thread-18] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: sun.net.dns.ResolverConfigurationImpl.notifyAddrChange0(Native Method) sun.net.dns.ResolverConfigurationImpl$AddressChangeListener.run(ResolverConfigurationImpl.java:144) 10:35:06.323 [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter - [report,40] - *************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.sdsEHS.hazardManagement.util.RedisPlanNumberGenerator required a bean of type 'org.springframework.data.redis.core.RedisTemplate' that could not be found. The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true) Action: Consider defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration. Disconnected from the target VM, address: '127.0.0.1:45918', transport: 'socket' Process finished with exit code 1
最新发布
11-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值