Feign 客户端响应验证 [英] Feign client response validation

查看:65
本文介绍了Feign 客户端响应验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个应用程序 A 和 B 使用 FeignClient 相互通信.作为应用程序 A,我希望对应用程序 B 返回的数据进行验证.如果我想验证请求参数,我可以轻松地使用 @Valid 注释并使用正确的 spring 验证注释来注释对象.回复怎么样?

I have two applications A and B communicating with each other using FeignClient. As an application A I want to have validation on the data that is returned by application B. If I want to validate request parameters I can easily use @Valid annotation and annotate object with correct spring validation annotations. What about response ?

@FeignClient()
public interface AccountClient {
   @PostMapping("/accounts/account/create")
   void createAccount(@Valid CreateAccountRequest request);

   @PostMapping("/accounts/account/get")
   AccountResponse getAccount(AccountRequest request);

}

public classs AccountResponse {
   @NotNull
   public String status;
}

以代码为例.我可以轻松地验证应用程序 B 中的 CreateAccountRequest.但是 AccountResponse 呢?在这种情况下,@NotNull 不起作用.我宁愿避免获得响应并手动检查 status != null 因为我会有更多这样的字段.

Code as an example. I can easily validate CreateAccountRequest in application B. But what about AccountResponse? In that case @NotNull is not working. I would prefer to avoid getting the response and manually checking if status != null cause I would have much more fields like this.

推荐答案

在这种情况下,如果将 @Validated 放在 AccountClient 接口上,然后响应验证应该可以工作@ValidgetAccount 方法.

In this case, the response validation should work if you place @Validated onto AccountClient interface and then @Valid onto getAccount method.

这是标准的 Spring 验证功能,不仅适用于 Feign

This is standard Spring validation feature, applicable not only for Feign

import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;

@Validated
@FeignClient
public interface AccountClient {
   @PostMapping("/accounts/account/create")
   void createAccount(@Valid CreateAccountRequest request);

   @Valid
   @PostMapping("/accounts/account/get")
   AccountResponse getAccount(AccountRequest request);

}

这篇关于Feign 客户端响应验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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