1.定义需要校验的类
@Data
public class Person {
private String name;
private int age;
}
2.编写校验器
@Component
public class PersonValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Person.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "name", "name.empty");
Person p = (Person) target;
if(p.getAge()<0){
errors.rejectValue("age","negativeValue");
}else if(p.getAge()>110){
errors.rejectValue("age","too.darn.old");
}
}
}
3.在Web中引用校验器,编写测试类
@RestController
public class TestController {
@Autowired
private PersonValidator personValidator;
@InitBinder
public void initBinder(WebDataBinder binder) {
System.out.println("initBinder");
binder.addValidators(personValidator);
}
/**
* 127.0.0.1:8886/get
* 测试Spring的数据校验
*
* @return
*/
@GetMapping(value = "/get")
public Object get(@Valid Person person, BindingResult bindingResult) throws IOException {
System.out.println(bindingResult.hasErrors());
System.out.println(bindingResult.getModel());
return bindingResult;
}
}
个人感觉有点鸡肋,没有hibernate的注解式数据校验好用