异常处理(二)---------Field * in * required a bean of type '*' that could not be found.

昨天在做SB项目整合Redis的时候报了这个错误。

以下是这个异常的完整信息

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-12-13 16:11:39.632 ERROR 3660 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field redisUtil in cn.yzstu.baldwinblog.controller.UserController required a bean of type 'cn.yzstu.common.utils.redis.RedisUtil' 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 'cn.yzstu.common.utils.redis.RedisUtil' in your configuration.

redisUtil:Controller中Autowire的一个Redis工具类

cn.yzstu.baldwinblog.controller.UserController:该Controller

ResultUtil:有关该类的信息如下

根据英文的提示是在配置中找不到一个指定自动注入类型的bean,经过多方排查得出结论: 
  正常情况下加上@Component(@Configuration注解包含了@Component注解功能)注解的类会自动被Spring扫描到生成Bean注册到spring容器中,既然他说没找到,也就是该注解被没有被spring识别,问题的核心关键就在application类的注解SpringBootApplication上 ,结合前几天遇到的扫描不到Mapper的问题思考,我感觉问题就是:我们本应设置我们应该扫描的文件夹,但是却没有设置。

然后我就想到了@ComponentScan注解,其实我们一般练手SB项目不会用到这个注解,因为启动类application.java中存在@SpringBootApplication时,spring会自动扫描当前包及当前包的各级子包,但是大家可以回头看一下我的@Bean注解的redisUtil的位置,是不在启动文件关联包下的,所以这时spring就扫描不到RedisUtil了。

解决办法:

不推荐使用我这种注解方法,直接扫描所有包,会影响项目启动时的加载速度

更多关于@Component注解的内容,可以自己去查一下

发布了45 篇原创文章 · 获赞 113 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/shouchenchuan5253/article/details/103529347