【问题标题】:Is there a way to integrate java bean validation api With Spring RestTemplate有没有办法将 java bean 验证 api 与 Spring RestTemplate 集成
【发布时间】:2017-07-26 17:19:27
【问题描述】:

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

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

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

    //...

  }

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

Employee emp = template.exchange("http:///someUrl", HttpMethod.GET, null);

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

  @Autowired
  private Validator validator;

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

【问题讨论】:

  • 您需要执行此操作的用例是什么?从技术上讲,我真的想不出一个你不想使用验证器对象的地方,除非它是某种代理服务......手动验证它是可以的,在某些情况下可能更有用。跨度>
  • 感谢您的回复。我只是想也许春天会有一些解决方案。我有很多 res 调用,我不想对从 restTemplate 返回的每个对象调用 validate 方法。

标签: java spring spring-mvc spring-boot bean-validation


【解决方案1】:

您可以将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);
    }
}

那么使用就很简单了,只要定义你的子类为RestTemplate bean即可。

完整样本:

@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());
        };
    }
}

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 2014-03-14
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多