feign的继承特性意义何在?

意义在于减少重复代码量。实现方式如下:

//请求接口
public interface DiscoveryClient {
    @RequestMapping("/ping/{hello}")
    String infoForServiceId(@PathVariable  String hello);
}
//feign客户端接口
@FeignClient(name = "discovery-client")
public interface DiscoveryFeignClient extends  DiscoveryClient{

}
//不使用继承特性时的controller及方法
@RequestMapping("/test/feign")
@RestController
public class TestFeignController {
    @Autowired
    DiscoveryFeignClient discoveryClient;
    @Autowired
    ZuulClient zuulClient;

	//不使用继承时,我们需要手工加上  @RequestMapping("/pingByServiceId/{hello}")
    @RequestMapping("/pingByServiceId/{hello}")
    public String infoForServiceId(@PathVariable String hello){
        String str = discoveryClient.infoForServiceId(hello);
        return str;
    }
}
//使用feigin继承特性的Controller
@RequestMapping("/test/feign")
@RestController
public class TestFeignInheritanceController implements DiscoveryClient {

    @Autowired
    DiscoveryFeignClient discoveryClient;

   //使用继承时,不需要加@RequestMapping("/ping/{hello}")  访问此方法时,使用ip/test/feign/ping/参数 的方式访问
    @Override
    public String infoForServiceId(@PathVariable String hello){

        String str = discoveryClient.infoForServiceId(hello);
        return str;
    }

}

使用继承的方式时,控制器中的方法可以继承接口中的requestMapping,不使用继承的时候需要手工定义。

经测试实现类方法中的参数注解@PathVariable、@RequestMapping、@RequestParam、@RequestHeader、@RequestBody都可以不添加。

	
@RequestMapping("/test/feign")
@RestController
public class TestFeignInheritanceController implements DiscoveryClient {

    @Autowired
    DiscoveryFeignClient discoveryClient;

    /**
    * @Title:
    * @Description:  测试根据服务name进行访问
    * @param
    * @return
    * @author huxx
    * @date 2019/11/8 下午3:24
    * @update
    */
    @Override
    public String infoForServiceId( String hello,String name,String age, Map<String,String> params){

        String str = discoveryClient.infoForServiceId(hello,name,age,params);
        return str;
    }

}

/**
* @Title: DiscoveryClient
* @Description:  测试使用feign的方式引用discovery-client服务
* @author huxx
* @date 2020/3/23 下午4:19
* @update
*/
public interface DiscoveryClient {
    @RequestMapping("/ping/{hello}")
    String infoForServiceId(@PathVariable  String hello, @RequestParam("name") String name, @RequestHeader("age") String age,@RequestBody Map<String,String> params);
}

feign的接口不可再继承其它interface,否则报错如下:Only single-level inheritance supported: RefactTestFeignService在SpringCloud中Feign支持继承,但是不支持多层继承
(他人结论,未亲自验证)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值