feign接口类扫瞄找不到的问题,required a bean of type 'xx.xx.xxxFeignClient' that could not be found

原创 2019-09-24 17:40 阅读(2728)次

在搭建spring cloud微服务时经常会遇到如下错误:

Description:

Field orderInfoFeignClient in com.mcu.stock.service.StockService required a bean of type 'com.mcu.common.feign.order.OrderInfoFeignClient' 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.mcu.common.feign.order.OrderInfoFeignClient' in your configuration.
就是feignclient扫瞄不到,在启动类上也加了@EnableFeignClients,也没用,甚至加了@ComponentScan("com.mcu")这样的配置也没用。代码如下:

@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients
@ComponentScan("com.mcu")
public class McuOrderApplication 
{
    public static void main(String[] args) {
        SpringApplication.run(McuOrderApplication.class, args);
    }

}
这样还是会报那个错,特别是我们把feignclient接口放到common模块工程里时,如果不注意包路径,很容易报这个错。

网上有人这样解决,就是在启动类的上把

@EnableFeignClients
改成如下:

@EnableFeignClients(basePackages = "com.mcu")

这样确实可以,但每个项目都要这样加,很烦(万一包名变了呢。。)

解决办法:

其实在建项目的初期就可以把这个问题避免掉,就是搭建微服务时把common工程这个模块以及其他业务模块的代码包路径整理清楚,比如:

common工程的包应该是:

com.mcu.common.feign

com.mcu.common.model

....

然后业务工程包应该是

com.mcu.controller

com.mcu.service

com.mcu.dao

启动类放在com.mcu包下。这样的话业务工程的启动类代码不需要配置扫瞄的包在哪,因为启动类就在所有的包父类包下,这就是利用spring boot的特性。启动类代码如下:

@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients
public class McuOrderApplication 
{
    public static void main(String[] args) {
        SpringApplication.run(McuOrderApplication.class, args);
    }

}
工程搭建的截图分享一下:

common模块结构:



order业务模块结构:




ps:我这边的mcu-common工程会被其他工程引入