Spring Rest Controller: how to selectively switch off validation

时光怂恿深爱的人放手 提交于 2019-12-18 07:48:21

问题


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) {
  ...

with

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)

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

@NotEmpty // (1)

of the RequestDTO should be ignored.

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?


回答1:


Short answer: Use Validation Groups:

@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)

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 {}

You can read more about these group constraints in Hibernate Validator documentation.



来源:https://stackoverflow.com/questions/35704351/spring-rest-controller-how-to-selectively-switch-off-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!