引言
在开发接口的时候,我们会对各种实体字段进行校验,为了提高代码的简洁性,少写点if判断,所以就会使用到Bean Validation(Bean Validation是Java定义的一套基于注解的数据校验规范).
自定义校验注解实现
定义校验注解:
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* 自定义手机验证注解
*/
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
//指定验证器
@Constraint(validatedBy = PhoneValidator.class)
public @interface Phone {
String message() default "手机号只能为520开头";
/**
* 验证组
* @return
*/
Class<?>[] groups() default { };
/**
* 负载策略
* @return
*/
Class<? extends Payload>[] payload() default { };
}
定义校验器
public class PhoneValidator implements ConstraintValidator<Phone,String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
String phone = Optional.ofNullable(value).orElse("");
Pattern pattern = Pattern.compile("150\\d{8}");
Matcher matcher = pattern.matcher(phone);
return matcher.matches();
}
}
进行验证
在需要校验的字段上加上@Phone注解
@Phone(message = "手机号只能为150开头")
private String phone;
在Controller的方法中加上@Validated注解
public ResponseResult update(
@PathVariable("id") @NotNull Long id,
@RequestBody @Validated UserDTO userDTO) {
int update = userService.update(id, userDTO);
if (update == 1) {
return ResponseResult.success("更新成功!");
} else {
return ResponseResult.failure(ErrorCodeEnum.UPDATE_FAILURE);
}
}
最后还需要给Controller加上@Validated注解.