异常信息
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0’: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/validation/ClockProvider
代码如下
@RequestMapping("/validate.json")
@ResponseBody
public JsonData validate(Car car)throws Exception{
logger.info("validate");
try {
Map<String, String> map = BeanValidator.validateObject(car);
if (map!=null&&map.entrySet().size()>0){
for(Map.Entry entry:map.entrySet()){
logger.info("{}->{}",entry.getKey(),entry.getValue());
}
}
}catch (Exception e){
e.printStackTrace();
}
return JsonData.success("hello,validation");
}
}
public class BeanValidator {
//获取工厂类
private static ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
//1.通过工厂类获取validator的实例
private static Validator validator = vf.getValidator();
/*
* @Method Validate 单个对象的校验
*
* @param T t 需要进行校验的bean对象
*
* @param groups 分组校验;
*
* @errors 存储校验的错误信息
*
* */
public static <T> Map<String,String> validate(T t,Class... groups){
//2.传入需要校验的bean获取validator的集合
Set<ConstraintViolation<T>> validateResult = validator.validate(t, groups);
//3.判断validator是否为空
if (validateResult.isEmpty()) {
//4.为空,则表示校验成功,返回空集合
return Collections.emptyMap();
//5.不为空,则表示有错误
}else {
//6.创建Errors集合
LinkedHashMap<String,String> errors = Maps.newLinkedHashMap();
//7.将错误信息用迭代器遍历Iterator
Iterator<ConstraintViolation<T>> iterator = validateResult.iterator();
while (iterator.hasNext()){
//遍历得到对象的每个属性
ConstraintViolation<T> violation = iterator.next();
//将校验的错误信息存入errors
errors.put(violation.getPropertyPath().toString(),violation.getMessage());
}
return errors;
}
}
/*
* @Method
*
* @param Collection 校验的bean集合
*
*@param errors.isEmpty 这里只要有错误信息就直接结束提交数据,返回错误信息到客服端;
*
* */
public static Map<String,String> ValidateList(Collection<?> collection){
//1.检查传入的参数集合非空
Preconditions.checkNotNull(collection);
//2.创建收集错误信息的集合
Map errors = new HashMap();
//3.迭代器迭代获取每一个对象
Iterator<?> iterator = collection.iterator();
do {
//4.校验成功返回空集合
if (!iterator.hasNext()){
return Collections.emptyMap();
//5.有错误,获取错误信息,并返回到错误信息集合
}else {
Object validation = iterator.next();
errors = validate(validation,new Class[0]);
}
//只要errors不为空就退出循环,使用do while()的原因是至少能进行一次判定;
}while (errors.isEmpty());
return errors;
}
/*
*@method validateObject 将上述的两种情况封装到一个方法中
*
* @param first bean对象
*
* @param objects 分组校验;
*
* */
public static Map<String,String> validateObject(Object first,Object... objects){
if(objects!=null&&objects.length>0){
//当传入数据类型是集合时:
return ValidateList(Lists.asList(first,objects));
}else {
//当传入时单个对象的时候
return validate(first,new Class[0]);
}
}
}