custom validator
1. Create an annotation MyConstraint, the validatedBy in @Constraint is used to specify the class of the validation operation
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
2. Create an implementation class of the ConstraintValidator interface. A in ConstraintValidator<A,T> is our own custom annotation, and T represents the annotated type. We use object here to indicate that all types can be customized by us annotations
public class MyConstraintValidator implements ConstraintValidator<MyConstraint,Object>{
// 初始化
@Override
public void initialize(MyConstraint constraintAnnotation) {
System.out.println("init");
}
// 执行校验操作
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
System.out.println("传进来的值:"+value);
System.out.println("上下文:"+context);
return false; //校验成功返回 true
}
}
3. Annotate the model and write a controller to verify it
public class User {
public interface UserSimpleView {}; // 定义一个简单的用户视图接口
public interface UserDetailView extends UserSimpleView {
}; // 定义一个详细的用户视图接口
@MyConstraint(message = "自定义注解测试")
private String username;
@NotEmpty(message = "密码不能为空")
private String password;
private Date birthday;
@JsonView(UserSimpleView.class)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@JsonView(UserSimpleView.class)
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping
public User create(@Valid @RequestBody User user){
System.out.println(user);
return user;
}
}
Utilize tools to test return values