1.引入依赖

<dependencies>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>7.0.5.Final</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.el</artifactId>
            <version>4.0.1</version>
        </dependency>
    </dependencies>

2.创建实体类的接口

package com.atguigu.Validator.Dao;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.Set;

public class PersonValidator implements Validator {

    //此校验用咋哪里
    @Override
    public boolean supports(Class<?> clazz) {
        return Person.class.equals(clazz);
    }

    //校验规则
    @Override
    public void validate(Object target, Errors errors) {
        //name不能为空
      /*   ValidationUtils.rejectIfEmpty 的四个参数
      errors是传如的参数
      name 属性名称
      name.empty 错误编码
      name is null提示信息
        */
        ValidationUtils.rejectIfEmpty(errors,"name","name.empty","name is null");
        //不能小于0  大于200
        Person p=(Person)target;
        if (p.getAge()<0){
            /*   errors.rejectValue 的四个参数
            age 属性名称
            age.val.error 错误编码
            age<0提示信息
             */
            errors.rejectValue("age","age.val.error","age<0");
        }else if (p.getAge()>200){
            errors.rejectValue("age","age.val.error.tooOld","age>200");
        }
    }
}

3.测试

 public static void main(String[] args) {
        //1.创建对象
        Person person=new Person();
        person.setName("JOJO");
        person.setAge(1800);
        //2.创建person对应的databinder
        DataBinder binder=new DataBinder(person);
        //3.设置校验器
        binder.setValidator(new PersonValidator());
        //4.调用方法执行校验
        binder.validate();
        //5.输出校验结果
        BindingResult bindingResult = binder.getBindingResult();
        System.out.println("bindingResult = " + bindingResult.getAllErrors());
    }