项目场景:
关于Spring Cloud微服务接入小框架记录
问题描述:
提示错误:@org.springframework.beans.factory.annotation.Autowired(required=true)
到百度或者其他博客上看都是关于@Autowired(required=true)的注入问题,这个问题也一度困扰了我很长时间
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-12-10 15:19:29 ERROR server-bu main org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter
***************************
APPLICATION FAILED TO START
***************************
Description:
Field mealOrderStruct in com.yeal.service.impl.OrderServiceImpl required a bean of type 'com.yeal.struct.OrderStruct' 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 'com.yeal.struct.OrderStruct' in your configuration.
Disconnected from the target VM, address: '127.0.0.1:50949', transport: 'socket'
Process finished with exit code 1
原因分析:
将这个该死的问题上百度一查会有很多博客告诉你设置成@Autowired(required=false)!诚不欺我,这个时候启动项目,不出意外还是一模一样的报错。如果你的不报错那么,你可以划走了·············
![错误位置](https://img-blog.csdnimg.cn/199016325f344cce93fb322d3dbfdff5.png) 可以看到正常注入的类都是有前面都是有一个绿色的箭头。很显然下面这个并没有被注入。 那么我第一个想到的是框架的问题,后来重新看了框架的使用,是没有问题的。
注入问题啊,注入到spring容器里面!知道问题所在就好解决问题了。
1.因为使用的mapstruct框架做DTO、entity、Vo之间的转换是用的
@Mapper(componentModel = "spring")
这个注解一直以为是用的@MapperScan(basePackages = {"com.yeal.**.mapper"})
去扫描的试了半天,结果不是。
2.突然想起来@SpringBootApplication
里面也是有扫描的注解也可以定义包
解决方案:
就在这个注解里面加上包的一个扫描就轻松搞定@SpringBootApplication(scanBasePackages = {"com.yeal"})
总结:
关于- @org.springframework.beans.factory.annotation.Autowired(required=true)报错,原因如下
1.可能是因为扫描注入问题:要么重复扫描,要么没有扫描到
2.@Autowired(required=false)