我有两个应用程序 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
接口(interface)上,然后将 @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);
}
关于java - 假装客户端响应验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59898096/