【已解决】springCould整合feign提示required a bean of type xxx that could not be found

12 篇文章 0 订阅
3 篇文章 0 订阅

【已解决】springCould整合feign提示required a bean of type xxx that could not be found

今天在使用springcloud整合feign的时候,提示


Description:

Field feignTestClient in com.example.xxxx.controller.xxxxx required a bean of type 'com.example.xxxx.remote.FeignTestClient' 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.xxxxx.xxxx.xxxxx.FeignTestClient' in your configuration.

 

先不废话,先上源码:

1、启动类,注解@EnableFeignClients 和 @EnableDiscoveryClient, 作为eureka客户端,服务发现

 

2、引入依赖

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
       </dependency>
       
       <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

 

3.定义feign接口 (另外accountserver服务要提供好相应的接口/account)

4.引入bean使用

 @Autowired
    private FeignTestClient feignTestClient;

 

 @GetMapping(value = "/feignclient")
    public String name() throws Exception {
        
        String name="name";
        name = feignTestClient.account();
        
        return "feignclient result:" +name;
    }
 

写好代码后运行, 发现还是不能用, 已经完全按照网上教程了。 调试了很久, 都没发现问题。

看到报错是  Consider defining a bean of type

心里想,这肯定是没有注入到spring容器里面,导致找到对应的这个bean, 但是明明已经设置了组件扫描路径了啊@ComponentScan({"com.example.demo.controller", 
    "com.example.demo.service"
})

然后查询@EnableFeignClients 的源码,发现注解里面有几个参数, 一想,会不会是因为EnableFeignClients不知道改扫描那个路径,不知道要注入那些bean,所以没法注入到spring里面呢?

 

好啦,谜题解开了,确实是FeignClients 要单独设置需要注解的路径和bean,才能交到spring那里托管, 解决方式有2种:

  1.直接注解对应的class

  @EnableFeignClients(basePackageClasses=FeignTestClient.class)

  2.类似spring组件扫描一样,扫描路径

 @EnableFeignClients(basePackages="com.example.*")

 

   2种都试过了,亲测有效。

 

总结:使用feignclines的时候,除了spring本身的组件扫描, 也要注明对应扫描的路径或者需要注入的bean。

           通过这个事情,发现其实网上很多博客教程都是有问题, 还是要多看看官方文档,多看看源码,问题就迎刃而解了。

如果问题,欢迎各位大佬指正。

 

 

  • 34
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值