SpringBoot自定义参数校验
@Data
public class User implements Serializable {
// 自定义校验,验证 username 必须以a开头,长度为5
@ValName
private String username;
@NotNull
private Integer age;
@ValName(require = false,message = "str不能为空")
private String str;
}
点进 @NotNull
的源码,复制过过来就行
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(NotNull.List.class)
@Documented
@Constraint(
validatedBy = {}
)
public @interface NotNull {
String message() default "{javax.validation.constraints.NotNull.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface List {
NotNull[] value();
}
}
复制到我们自己的注解
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = ValNameValidator.class)//自定义的参数校验类
public @interface ValName {
boolean require() default true;
String message() default "名称不符合规范,只能以a开头,长度为5";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
自定义参数校验类ValNameValidator
,实现ConstraintValidator
public class ValNameValidator implements ConstraintValidator<ValName, String> {
// 保存 require的值,获取到注解中的
boolean require = true;
@Override
public void initialize(ValName constraintAnnotation) {
this.require = constraintAnnotation.require();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
// a开头,长度为5
if (require) {
if (value.charAt(0) == 'a' && value.length() == 5) {
return true;
}
} else {
//不需要就验证,有值就行
if (!StringUtils.isEmpty(value)) {
return true;
}
}
return false;
}
}
controller使用
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/login")
public String login(@Valid User user, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return bindingResult.getFieldError().getDefaultMessage();
}
return user.toString();
}
}
错误:
正确: