openFeign调用问题:required a bean of type 'xxx' that could not be found.
场景:
服务B是一个公共的服务,打包成jar后给其他服务使用
package com.testB.seviceB.remote; //服务B中定义的feign接口 @FeignClient(value = "service-c", path = "/service-c") public interface ServiceBClient { xxxx }
服务A中引用服务B中定义的Feign接口
package com.testA.serviceA.service; @Service public class CallServcieB { //引用服务B中的Feign接口 @Autowired private ServiceBClient serviceBClient; }
启动服务A 是报错:声明的 ServiceBClient 找不到
2024-07-19 17:39:58.008 ERROR 47544 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Field serviceBClient in com.testA.serviceA.service.CallServcieB required a bean of type 'com.testB.seviceB.remote.ServiceBClient' 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.testB.seviceB.remote.ServiceBClient' in your configuration.
报错原因:
上面的报错是因为,启动类中Feign默认扫描的是当前服务A的包,需要将引用的服务B的类所在包的路径,也加入Feign的扫描路径中
解决:
修改启动类上Feign的扫描路径,将服务B的中的Feign路径加进来,这样就可以识别到引入的服务B的接口了。
com.testA.serviceA 是服务A的路径
com.testB.seviceB.remote 是服务B的Feign接口路径
package com.testA.serviceA; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @EnableDiscoveryClient //加入引用的包路径 @EnableFeignClients(basePackages = {"com.testA.serviceA", "com.testB.seviceB.remote"}) @SpringBootApplication public class ServiceAApplication { public static void main(String[] args) { SpringApplication.run(ServiceAApplication.class, args); } }