第一步 创建配置类,配置MethodValidationPostProcessor
package com.atguigu.Validator3; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; @Configuration @ComponentScan("com.atguigu.Validator3") public class ValidationConfig { @Bean public MethodValidationPostProcessor validationPostProcessor(){ return new MethodValidationPostProcessor(); } }
第二步 创建实体类,使用注解设置校验规则
package com.atguigu.Validator3; import jakarta.validation.constraints.*; public class User { @NotNull private String name; @Max(120) @Min(0) private int age; @Pattern(regexp = "^1(3|4|5|7|8)\\d{9}$",message = "手机号码格式错误") @NotBlank(message = "手机号不能为空") private String phone; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setPhone(String phone) { this.phone = phone; } }
第三步 定义Service类,通过注解操作对象
package com.atguigu.Validator3; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; @Service @Validated public class Myservice { public String TestMethod(@NotNull @Valid User user) { return user.toString(); } }
第四步 测试
package com.atguigu.Validator3; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestUser { public static void main(String[] args) { ApplicationContext context= new AnnotationConfigApplicationContext(ValidationConfig.class); Myservice myservice = context.getBean(Myservice.class); User user=new User(); user.setAge(18); user.setName("yoyo"); user.setPhone("15299698836"); myservice.TestMethod(user); } }