[英]Spring boot - rest client from rest controller interface
使用 spring 启动 2.6.0(或更高版本)是否可以从 controller 接口生成 rest 客户端?
我想知道是否可以像下面的用例那样构建 spring 应用程序。
Spring 应用A需要调用spring 应用B rest接口
Spring 应用程序 B 是一个多模块项目,可生成服务器 jar 和 api Z68995FCBF432492D150484DAC40
Spring应用A导入B的API jar
Spring application A uses controller interface from B Api jar to make a rest client based on spring annotations.
B Api jar:
@RestsController
public interface MyApplicationAPI {
@GetMapping("/api/some-endpoint)
public SomeDto someEndpoint(SomeDTO obj);
}
B服务器jar:
public class BApplicationAPIImpl implements MyApplicationAPI {
public SomeDto someEndpoint(SomeDTO obj) {
return xxx;
最后在 A 应用程序中:
MyApplicationAPI restClient = Some.magic(MyApplicationAPI.class, "http://bappurl.com")
SomeDto response = restClient.someEndpoint(param);
我相信框架 RestEasy 支持类似的方法,但你必须依赖 JAXRS 注释。
spring 框架有类似的东西吗? 或者甚至更好的是 spring 中已经有类似的东西 - 我更愿意依赖 spring 内部库和工具,而不是导入整个 resteasy 和 jaxrs。
Spring Framework 6(和 Spring Boot 3)将具有声明性 HTTP 接口( 参见文档)。 但是,它们不会使用与控制器相同的注释,而是使用单独的注释。 因此,您无法为 controller 和客户端使用相同接口的示例。
文档中的代码片段:
interface RepositoryService { @GetExchange("/repos/{owner}/{repo}") Repository getRepository(@PathVariable String owner, @PathVariable String repo); // more HTTP exchange methods... }
初始化(您问题中的Some.magic()
部分)可以使用WebClient
完成。 从同一文档中可以看出:
WebClient client = WebClient.builder().baseUrl("https://api.github.com/").build(); HttpServiceProxyFactory factory = WebClientAdapter.createHttpServiceProxyFactory(client); factory.afterPropertiesSet(); RepositoryService service = factory.createClient(RepositoryService.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.