springboot annotation

Posted May 25, 20203 min read

SpringBoot annotation verification

Annotation Type of Action Explanation
@NotNull Any type Property cannot be null
@NotEmpty Collection Collection cannot be null and size is greater than 0
@NotBlanck String, character Character class cannot be null, and the length is greater than 0 after removing spaces
@AssertTrue Boolean, boolean Boolean attribute must be true
@Min Number Type(Atomic and Packaging) Limit the Minimum Number(Integer)
@Max Same as @Min The maximum value of the limited number(integer)
@DecimalMin Same as @Min The minimum value of the limited number(string, can be a decimal)
@DecimalMax Same as @Min The maximum value of the limited number(string, can be a decimal)
@Range Number type(atomic and packaging) Limited number range(long integer)
@Length String Limit String Length
@Size Collection Limited Collection Size
@Past Time, Date Must be a past time or date
@Future Period, time Must be a future time or date
@Email String Must be a mailbox format
@Pattern String, character Regular matching string

Custom annotation verification

1 . Write a verification note

//We can directly copy the annotations in the system, such as @Min, to our new annotations, and then modify them as needed.
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
//Annotated implementation class.
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {
    //Check the wrong default information
    String message() default "There is a problem with the mobile phone number format";

    //Whether to force verification
    boolean isRequired() default false;

    Class <?> []Groups() default {};

    Class <? Extends Payload> []payload() default {};
}

2 . Write specific implementation class

We know that the annotation is just a mark, and the real logic must be implemented in a specific class. The annotation in the previous step specifies the class that implements the verification function as IsMobileValidator.

//Custom annotations must implement the ConstraintValidator interface, the two parameters inside
//The first is a specific note to be verified
//The second one is the parameter type for verification
public class IsMobileValidator implements ConstraintValidator <IsMobile, String> {

    private boolean required = false;

    private static final Pattern mobile_pattern = Pattern.compile("1 \\ d {10}");
    //Tool method to determine whether it is a mobile phone number
    public static boolean isMobile(String src) {
        if(StringUtils.isEmpty(src)) {
            return false;
        }
        Matcher m = mobile_pattern.matcher(src);
        return m.matches();
    }

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.isRequired();
    }

    @Override
    public boolean isValid(String phone, ConstraintValidatorContext constraintValidatorContext) {
        //Whether it is the realization of mobile phone number
        if(required) {
            return isMobile(phone);
        } else {
            if(StringUtils.isEmpty(phone)) {
                return true;
            } else {
                return isMobile(phone);
            }
        }
    }

}

3 . Test the function of custom annotations

@Data
public class User {
    @NotNull
    @Size(min = 2, max = 30, message = "Please check the length of the name if there is any problem")
    private String name;

    @NotNull
    @Min(18)
    private Integer age;

    //This is the newly added note
    @IsMobile
    private String phone;
}

4 . Verification

Then use @Validated and BindingResult classes in each interface of the controller

The @Validated annotation is used to verify an input parameter, and the message after verification is bound to the BindingResult class:

@PostMapping("/test")
@ApiOperation(value = "Test", notes = "", response = Result.class)
public Result test(@ApiParam(name = "test", value = "Parameter", required = true) @Validated @RequestBody Test test, BindingResult bindingResult) {
    if(bindingResult.hasErrors()) {
        String errorMsg = bindingResult.getFieldError(). GetDefaultMessage();
        return Result.error(errorMsg);
    }
    return Result.ok("Parameter verification passed");
}