有没有办法将 java bean 验证 api 与 Spring RestTemplate 集成

use*_*466 6 java spring spring-mvc bean-validation spring-boot

有没有办法将 spring RestTemplate 与 JavaBean 验证 api 集成。?

我知道弹簧控制器有一个集成。您可以添加@Valid请求正文参数,如果 Employee 无效,您将收到MethodArgumentNotValidException异常。您可以在异常处理程序类中处理它。

  @PostMapping(value = "/add", produces = APPLICATION_JSON_VALUE)
  public ResponseEntity<String> addEmployee(
       @RequestBody @Valid Employee emp) {

    //...

  }
Run Code Online (Sandbox Code Playgroud)

但是我想要的是类似的方式来验证来自 spring restTemplate 的响应,就像我这样调用时一样 - 我想从 spring 中获得相同的(或者可能是其他的)异常。

Employee emp = template.exchange("http:///someUrl", HttpMethod.GET, null);
Run Code Online (Sandbox Code Playgroud)

我知道我可以像这样注入验证器并在响应时调用 validator.validate(..) 。

  @Autowired
  private Validator validator;
Run Code Online (Sandbox Code Playgroud)

但我不想每次都手动进行。

Boh*_*nko 6

您可以RestTemplate在从原始数据中提取响应后立即对响应进行子类化和验证。

例子:

public class ValidatableRestTemplate extends RestTemplate {

    private final Validator validator;

    public ValidatableRestTemplate(Validator validator) {
        this.validator = validator;
    }

    @Override
    protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException {
        final T response = super.doExecute(url, method, requestCallback, responseExtractor);
        Object  body;
        if (response instanceof ResponseEntity<?>) {
            body = ((ResponseEntity) response) .getBody();
        } else {
            body = response;
        }
        final Set<ConstraintViolation<Object>> violations = validator.validate(body);
        if (violations.isEmpty()) {
            return response;
        }

        throw new ConstraintViolationException("Invalid response", violations);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法很简单,只需将您的子类定义为RestTemplatebean。

完整样本:

@SpringBootApplication
public class So45333587Application {

    public static void main(String[] args) { SpringApplication.run(So45333587Application.class, args); }

    @Bean
    RestTemplate restTemplate(Validator validator) { return new ValidatableRestTemplate(validator); }

    public static class ValidatableRestTemplate extends RestTemplate {
        private final Validator validator;

        public ValidatableRestTemplate(Validator validator) { this.validator = validator; }

        @Override
        protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException {
            final T response = super.doExecute(url, method, requestCallback, responseExtractor);
            Object  body;
            if (response instanceof ResponseEntity<?>) {
                body = ((ResponseEntity) response).getBody();
            } else {
                body = response;
            }
            final Set<ConstraintViolation<Object>> violations = validator.validate(body);
            if (violations.isEmpty()) {
                return response;
            }

            throw new ConstraintViolationException("Invalid response", violations);
        }
    }

    @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
    public static class Post {
        @Min(2) // change to '1' and constraint violation will disappear
        private Long   id;
        private Long   userId;
        private String title;
        private String body;

        @Override
        public String toString() { 
            return String.format("Post{id=%d, userId=%d, title='%s', body='%s'}", id, userId, title, body); 
        }
    }

    @Bean
    CommandLineRunner startup(RestTemplate restTemplate) {
        return args -> {
            final ResponseEntity<Post> entity = restTemplate.exchange("https://jsonplaceholder.typicode.com/posts/1", HttpMethod.GET, null, Post.class);
            System.out.println(entity.getBody());
        };
    }
}
Run Code Online (Sandbox Code Playgroud)