Spring Rest Controller:如何有选择地关闭验证 [英] Spring Rest Controller: how to selectively switch off validation
问题描述
在我的控制器中,我有一种创建实体的方法
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屋!