springboot使用Fegin,创建服务接口,在controller里面注入Feign接口对象,结果启动报错。
Description:
Field cityClient in com.example.controller.HttpController required a bean of type 'com.example.service.CityClient' 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.example.service.CityClient' in your configuration.
但是看了bean的注入是没有问题的,后来发现是Application的@EnableFeignClients和@Component这两个注解冲突了。
注解 @EnableFeignClients 与 @ComponentScan 有冲突,两种注解都会搜索注入指定目录中的 bean 。@EnableFeignClients 引入了 FeignClientsRegistrar 类,实现了 Spring 的bean 资源的加载。
FeignClientsRegistrar中registerFeignClients方法获取了@EnableFeignClients注解中的basepackage 属性值,并进行注入。如果两种注解都使用时,其中@EnableFeignClients会覆盖 @ComponentScan 中指定的目录,从而恢复到默认目录。
解决方法:
1、在注解@EnableFeignClients指定clients,原来我代码里没有指定clients

2、可以将 FeignClient 这个 bean 放在和 Application 启动类同级目录(这个我没试过,应该可以)

本文探讨了在SpringBoot项目中使用Feign时遇到的注入冲突问题,具体表现为Application中@EnableFeignClients与@Component注解冲突导致的bean注入失败。文章详细分析了问题原因,指出这两种注解都会搜索并注入指定目录中的bean,而@EnableFeignClients会覆盖@ComponentScan的目录设置,最终提供了有效的解决方案。

6483

被折叠的 条评论
为什么被折叠?



