用于对添加了校验注解的对象,如果没有直接赋值而是间接解析的话,需要校验。

 

public class ValidatorUtil {

	private static Validator validator = 
	((HibernateValidatorConfiguration) Validation.byProvider(HibernateValidator.class).configure()).failFast(true).buildValidatorFactory().getValidator();

	/**
	* 实体校验
	*
	* @param obj
	* @throws LocalBindException
	*/
	public static <T> void validate(T obj) throws Exception {
		Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, new Class[0]);
		if (constraintViolations.size() > 0) {
			ConstraintViolation<T> validateInfo = (ConstraintViolation<T>) constraintViolations.iterator().next();
			// validateInfo.getMessage() 校验不通过时的信息,即message对应的值
			throw new Exception(validateInfo.getMessage());
		}
	}
}