该工具类可以主动进行javax.validation校验
import org.apache.commons.collections.CollectionUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import java.util.Set;
/**
* validate校验工具类
*
* @author g30003063
* @since 2020-05-20
*/
public final class ValidateUtils {
private ValidateUtils() {
}
/**
* validate主动校验方式
*
* @param validateObject 进行校验的对象
* @param <T> 传递的校验类型
* @throws ServiceException 服务异常
*/
public static <T> void validate(@Valid T validateObject) throws ServiceException {
Set<ConstraintViolation<@Valid T>> validateSet = Validation
.buildDefaultValidatorFactory()
.getValidator()
.validate(validateObject);
if (CollectionUtils.isNotEmpty(validateSet)) {
String messages = validateSet.stream()
.map(ConstraintViolation::getMessage)
.reduce((m1, m2) -> m1 + ";" + m2)
.orElse("parameter error!" + validateObject);
throw new RuntimeException(messages);
}
}
}