Spring Cloud Feign客户端可以与Spring Web Controller共享接口吗? [英] Can a Spring Cloud Feign client share interface with an Spring Web Controller?

查看:462
本文介绍了Spring Cloud Feign客户端可以与Spring Web Controller共享接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring MVC和Feign Client(使用Spring Cloud)构建端点和客户端.我曾想过,既然两端都需要具有相同的注释-并且它们必须几乎保持同步.也许我可以在一个接口中定义它们,并让两端实现它.

Building an endpoint and client with Spring MVC and Feign Client (with spring cloud). I had the thought that since both ends need to have the same annotations - and that they have to be pretty much in sync. Maybe I could define them in an interface and have the two ends implement that.

对其进行测试,令我感到惊讶的是它确实适用于Spring Web端.

Testing it out I was somewhat surprised that it actually works for the Spring Web end.

但是我找不到适合Feign客户的方法.

But it I cannot find a way to do the same for a Feign client.

我基本上有界面:

@RequestMapping("/somebaseurl")
public interface ServiceInterface {
  @RequestMapping(value = "/resource/{identifier}", method = RequestMethod.POST)
  public SomeResource getResourceByIdentifier(String identifier);
}

然后是RestController

And then the RestController

@RestController
public class ServiceController implements ServiceInterface {
    public SomeResource getResourceByIdentifier(@PathVariable("identifier") String identifier) {
    // Do some stuff that gets the resource
        return new SomeResource();
    }
}

最后是假客户

@FeignClient("serviceName")
public interface ServiceClient extends ServiceInterface {
}

Feign客户端似乎未读取继承的注释.那么,还有其他方法可以完成同一件事吗?在哪里可以使ServiceInterface成为Feign客户端而无需直接对其进行注释?

The Feign client seems to not read the inherited annotations. So is there some other way I can accomplish the same thing? Where I can make the ServiceInterface into Feign client without annotating it directly?

推荐答案

Spring Cloud文档:

假继承支持

Feign通过单继承接口支持样板API.这允许对常见操作进行分组 进入方便的基本接口.与Spring MVC一起,您可以 与您的REST端点和Feign客户共享相同的合同.

Feign Inheritance Support

Feign supports boilerplate apis via single-inheritance interfaces. This allows grouping common operations into convenient base interfaces. Together with Spring MVC you can share the same contract for your REST endpoint and Feign client.

UserService.java

UserService.java

public interface UserService {

    @RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
    User getUser(@PathVariable("id") long id);
}

UserResource.java

UserResource.java

@RestController
public class UserResource implements UserService {

}

UserClient.java

UserClient.java

@FeignClient("users")
public interface UserClient extends UserService {

}

这篇关于Spring Cloud Feign客户端可以与Spring Web Controller共享接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆