假装客户端响应验证

Feign client response validation

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

@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 因为我会有更多这样的字段。

在这种情况下,如果您将 @Validated 放在 AccountClient 界面上,然后将 @Valid 放在 getAccount 方法上,响应验证应该会起作用。

这是标准的 Spring 验证功能,不仅适用于 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);

}