本文目录
4.1 方案一:扩大注解 @EnableFeignClients扫描的包的范围
4.2 方案二:在注解@EnableFeignClients指定clients
一、背景描述
微服务项目,spring boot (v2.1.5.RELEASE) ,今天在ServiceA微服务里添加一个功能,通过FeignClient调用ServiceB的接口。
在本项目里通过@Autowired自动注入方式注入客户端接口
@Autowired
private ScreenSaverClient screenSaverClient;
然后启动项目,结果就报 APPLICATION FAILED TO START 项目启动失败。
二、报错信息
报错内容如下图所示:
三、错误原因
报这个错,是因为启动类里的注解 @EnableFeignClients没有扫描到这个包,在本项目里是没有扫描到com.iot.basic.iotsmarthome.api.client.screensaver.ScreenSaverClient这个。
以下是本项目的错误的启动类代码:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@ComponentScan(basePackages = {"com.uiotsoft.back","com.uiotsoft.framework"})
@EnableFeignClients(basePackages = {"com.uiotsoft.back.operation.facade.feign"})
@ServletComponentScan(basePackages ={"com.uiotsoft.back.operation.config"} )
@EnableSwagger2
@EnableHystrix
@EnableConfigurationProperties
public class OperationApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(OperationApplication.class, args);
}
}
四、解决方案
方案有多种,这里先写两种,以后再更新:
4.1 方案一:扩大注解 @EnableFeignClients扫描的包的范围
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@ComponentScan(basePackages = {"com.uiotsoft.back","com.uiotsoft.framework"})
@EnableFeignClients(basePackages = {"com.uiotsoft"})
@ServletComponentScan(basePackages ={"com.uiotsoft.back.operation.config"} )
@EnableSwagger2
@EnableHystrix
@EnableConfigurationProperties
public class OperationApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(OperationApplication.class, args);
}
}
网上有说“将 FeignClient 这个 bean 放在和 Application 启动类同级目录”,其道理和作用是和方案一相同的。
4.2 方案二:在注解@EnableFeignClients指定clients
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@ComponentScan(basePackages = {"com.uiotsoft.back","com.uiotsoft.framework"})
@EnableFeignClients(basePackages = {"com.uiotsoft.back.operation.facade.feign"}, clients = ScreenSaverClient.class)
@ServletComponentScan(basePackages ={"com.uiotsoft.back.operation.config"} )
@EnableSwagger2
@EnableHystrix
@EnableConfigurationProperties
public class OperationApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(OperationApplication.class, args);
}
}
当然方案二有个弊端,就是项目里存在多个clients(需要调用很多其他的服务时)的时候,就需要指定很多个,所以如果通过FeignClient调用多个服务的时候,用方案一比较合适。
完结!
以下不用看,只是方便被搜索到
***************************
APPLICATION FAILED TO START
***************************Description:
Parameter 0 of constructor in com.uiotsoft.back.operation.facade.service.impl.ScreenSaverClientServiceImpl required a bean of type 'com.uiotsoft.basic.iotsmarthome.api.client.screensaver.ScreenSaverClient' 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.uiotsoft.basic.iotsmarthome.api.client.screensaver.ScreenSaverClient' in your configuration.