public class ValidationUtil {
// 线程安全
private static Validator failFastValidator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
// 快速失败的
failFastValidator = Validation.byProvider(HibernateValidator.class)
.configure().failFast(true) // 配置快速失败
.buildValidatorFactory().getValidator();
}
public static List<String> validFailFast(UserInfo userInfo, Class<?>... groups){
// 如果被校验对象userInfo没有校验通过,则set里面就有校验信息
Set<ConstraintViolation<UserInfo>> set = failFastValidator.validate(userInfo,groups);
List<String> list = set.stream().map(v -> "属性:" + v.getPropertyPath() +
",属性的值:"
+ v.getInvalidValue() + ",校验不通过的提示信息:" + v.getMessage()
+",消息模板:"+v.getMessageTemplate()) // el表达式还没被解析成值的时候
.collect(Collectors.toList());
return list;
}
}
# 测试
public class ValidationTest {
public static void main(String[] args) {
UserInfo userInfo = new UserInfo();
userInfo.setName("zhaodaowen");
userInfo.setAge(18);
userInfo.setEmail("2025186764@qq.com");
userInfo.setPhone("13312345678");
userInfo.setBirthDay(LocalDateTime.now().minusDays(1));
userInfo.setPersonalPage("http://www.roadjava.com");
List<String> list = ValidationUtil.validFailFast(userInfo,UserInfo.Add.class,Default.class);
System.out.print(list);
}
}
public class ValidationUtil {
// 线程安全
private static ExecutableValidator executableValidator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
// 快速失败的
failFastValidator = Validation.byProvider(HibernateValidator.class)
.configure().failFast(true) // 配置快速失败
.buildValidatorFactory().getValidator();
// 校验入参或返回值的
executableValidator = validator.forExecutables();
}
public static <T> List<String> validNotBean(T object,
Method method,
Object[] parameterValues,
Class<?>... groups) {
Set<ConstraintViolation<T>> set = executableValidator.validateParameters(object, method, parameterValues, groups);
List<String> list = set.stream().map(v -> "属性:" + v.getPropertyPath() +
",属性的值:"
+ v.getInvalidValue() + ",校验不通过的提示信息:" + v.getMessage()
+",消息模板:"+v.getMessageTemplate()) // el表达式还没被解析成值的时候
.collect(Collectors.toList());
return list;
}
}
public class UserInfoService {
/*
方法非bean类型的入参校验
1.方法参数前加注解
2.执行入参校验,真正要用的话可以使用aop编程的思想来使用
*/
public String getByName(@NotNull String name) {
// 执行入参校验 aop
StackTraceElement st = Thread.currentThread().getStackTrace()[1];
String methodName = st.getMethodName(); // getByName
Method method = null;
try {
method = this.getClass().getDeclaredMethod(methodName, String.class);
}catch (Exception e) {
e.printStackTrace();
}
List<String> list = ValidationUtil.validNotBean(this, method, new Object[]{name});
// 打印校验结果
System.out.println(list);
return "ok";
}
}
# 测试
public class App {
public static void main(String[] args) {
UserInfoService userInfoService = new UserInfoService();
userInfoService.getByName(null);
}
}