Spring Rest Controller:如何有选择地关闭验证 [英] Spring Rest Controller: how to selectively switch off validation

查看:174
本文介绍了Spring Rest Controller:如何有选择地关闭验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我有一种创建实体的方法

In my controller I have a method for creating an entity

import javax.validation.Valid;
...
@RestController
public class Controller {

  @RequestMapping(method = RequestMethod.POST)  
  public ResponseEntity<?> create(@Valid @RequestBody RequestDTO requestDTO) {
  ...

使用

import org.hibernate.validator.constraints.NotEmpty;
...
public class RequestDTO
    @NotEmpty // (1)
    private String field1;
    //other fields, getters and setters.

我想添加一个控制器方法

I want to add a controller method

update(@Valid @RequestBody RequestDTO requestDTO)

,但在这种方法中,应允许field1为空或为空,即行

but in this method it should be allowed for field1 to be empty or null, i.e. the line

@NotEmpty // (1)

RequestDTO中的

应该被忽略.

of the RequestDTO should be ignored.

我该怎么做?我是否必须编写一个看起来与RequestDTO完全相同但没有注释的类?还是通过继承有某种可能性?

How can I do this? Do I have to write a class that looks exactly the same like RequestDTO, but does not have the annotation? Or is it somehow possible via inheritance?

推荐答案

简短答案:使用验证组:

@NotEmpty(groups = SomeCriteria.class)
private String field1;

并在方法处理程序参数中引用您想要的组:

And reference your intended group in method handler parameters:

public ResponseEntity<?> create(@Validated(SomeCriteria.class) @RequestBody RequestDTO requestDTO)

在上面的示例中,将应用SomeCriteria组中的验证,而其他验证将被忽略.通常,这些验证组被定义为空接口:

In the above example, validations in the SomeCriteria group will be applied and others going to be ignored. Usually, these validation groups are defined as empty interfaces:

public interface SomeCriteria {}

您可以在 Hibernate Validator文档中了解有关这些组约束的更多信息.

这篇关于Spring Rest Controller:如何有选择地关闭验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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