一、@FeignClient常规用法说明
假设我们有一个IFactoryUser maven模块,其UserController层代码如下。
@RestController
@RequestMapping(value = "/user")
@Api(tags = "用户管理接口")
@Slf4j
public class UserController extends BaseController {
@Resource
private IUserService userService;
@ApiOperation(value = "添加用户")
@PostMapping("/insertUser")
public ReturnBean insertUser(@RequestBody UserBean user) {
userService.insertUser(user);
return new ReturnBean();
}
}
如上代码,假如我们需要在其他模块中使用到该Controller的insertUser方法,我们就可以使用@FeignClient注解,如下所示。
@FeignClient(value = "IFactoryUser") // UserController所在的模块名称
@RequestMapping("/user")
public interface IUserService {
@PostMapping("/insertUser")
ResponseMsg insertUser(@RequestBody UserBean user);
}
二、问题
1、类冗余
如上代码,我们在其他模块中使用IFactoryUser模块的insertUser方法的时候,就必须要有一个UserBean类,可能导致冗余。经过测试发现可以使用JSONObject对象替代,对象属性对应键值对,如下所示。
@FeignClient(value = "IFactoryUser") // UserController所在的模块名称
@RequestMapping("/user")
public interface IUserService {
@PostMapping("/insertUser")
ResponseMsg insertUser(@RequestBody JSONObject user);
}
2、找不到类
开发过程中,还遇到注入失败的情况,错误日志如下。
***************************
APPLICATION FAILED TO START
***************************
Description:
Field payService in com.gmd.controller.PayController required a bean of type 'com.gmd.service.IUserService' 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.gmd.service.IUserService' in your configuration.
原因是对应的IFactoryPayApplication启动类没有加如下注解。
@EnableEurekaClient
也就说如果你要使用@FeignClient注解,就必须在对应SpringBoot启动类上加@EnableEurekaClient注解。