Spring Bean Validaiton ~ Bean Bari Deshon ~

Bean Validation

Describe a sample based on REST communication using Spring Framework.

What is Bianbari?

Check the value of RequestBody sent from the client. There are several types of check contents.

etc...

Sample for the time being

A sample that just performs validation on the controller.

SampleContorller.java


@RestController
@RequestMapping("validation")
public class SampleController {

  //Just validate
  @PostMapping
  public SampleResource validation(
        @RequestBody @Validated SampleResource resource) {
    return resource;
  }
}
@Getter
@Setter
public class SampleResource {
  @NotNull
  @Size(min = 5, max = 30)
  @Pattern(regexp = "[a-zA-Z0-9]*")
  private String message;
}
Annotation Description
@NotNull Prohibit Null
@Size {min}that's all{max}Make sure that
@Pattern Confirm that it is the specified pattern

more Bean Validation

Validation of nested classes

Specify @Valid in the field.

SampleContorller.java


Above sample controller together
@Getter
@Setter
public class SampleResource {
  @Valid
  @NotNull
  private SampleNestResource nestResource;
}

You are validating a nested class with @Valid. If nestResource is not sent, Null will be bound to the field and the validation specified in SampleNestResource will not be executed, so it is required by @NotNull.

@Getter
@Setter
public class SampleNestResource {
  @NotNull
  @Size(min = 5, max = 30)
  @Pattern(regexp = "[a-zA-Z0-9]*")
  private String message;
}

Check in Collection

When Collection such as List is specified in the field, the validation specification of the class without Collection and the validation specification for the field are different.

SampleContorller.java


Above sample controller together
@Getter
@Setter
public class SampleResource {
  
  @Size(min = 2)
  private List<@NotNull String> strList;
}

Check if the List element of the field is 2 or more with @Size Make sure String in List is not Null with @NotNull

Validation error handling

If no handling is performed, MethodArgumentNotValidException will occur. In RestController, no error is entered in BindingResult, so get the error contents with Errors.

SampleContorller.java


@RestController
@RequestMapping("validation")
public class SampleController {

  //Just validate
  @PostMapping
  public SampleResource validation(
        @RequestBody @Validated SampleResource resource,
        Errors errors) {
    if (errors.hasErrors()){
      throw new RuntimeException();
    }

    return resource;
  }
}

Recommended Posts

Spring Bean Validaiton ~ Bean Bari Deshon ~
Spring bean life cycle
call spring management bean from pojo