SpringBoot uses JSR303 custom verification annotations

But sometimes the annotations it provides do not meet our requirements. For example, we require that the field color must be one of the three values ​​"red, blue, yellow". At this time, we need to write our own judgment logic. You You can customize a method to judge in other places, but since JSR303 is used, in order to unify the code, you can customize verification annotations.

1, to the field coloron a custom label notes @ListValue, these values on to write

@ListValue(vals = {"red", "blue", "yellow"})
private String color;

2. Create notes @ListValue, you can refer to the official notes, for example @NotNull, we only need to modify a few places of the notes below

// Custom constraint validator
@Constraint (validatedBy = {ListValueConstraintValidator.class})
@Documented
@Target ({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention (RUNTIME)
public @interface ListValue {

  // The name of the error message in the configuration file
  String message () default "{com.sjl.common.valid.ListValue.message}";

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

    Class <? Extends Payload> [] payload () default {};
 
    // Type of custom value
    String [] vals () default {};
}

3. Create a custom constraint checker, inheritance ConstraintValidator, the first generic type is a custom annotation, the second is the type of check value, that is, the type of the field marked by the annotation

public class ListValueConstraintValidator implements ConstraintValidator<ListValue,String>{
   
    private static Set<String> set = new HashSet<>();

    @Override
    public void initialize(ListValue constraintAnnotation) {
        for (String val : constraintAnnotation.vals()) {
            set.add(val);
        }
    }

    / **
    * Judge whether it passes the verification
    *
    * @param value Incoming value
    * @param context
    * @return
    * /
    @Override
    public boolean isValid (String value, ConstraintValidatorContext context) {
        return set.contains (value);
    }
}

4, resourcescreate a directory ValidationMessages.propertiesprofile keyis the second step messagedefaults set, valuea custom error messages

com.sjl.common.valid.ListValue.message = Must submit the specified value

So far, all the work has been completed, the custom annotation @ListValuecan work, of course, this is just a very simple check, but much the same way.

Guess you like

Origin www.linuxidc.com/Linux/2020-04/162853.htm