Created
August 23, 2021 02:46
-
-
Save codethereforam/b6d814f5d5f159d9c85e89fd0db46287 to your computer and use it in GitHub Desktop.
javax校验工具类
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.hibernate.validator.HibernateValidator; | |
import javax.validation.ConstraintViolation; | |
import javax.validation.Validation; | |
import javax.validation.Validator; | |
import java.util.Objects; | |
import java.util.Set; | |
/** | |
* javax校验工具类 | |
* | |
* <p> | |
* 目前只实现了fail-fast的一些校验方法,如果需要fail-over的,添加以下代码,模仿已有的方法写几个方法即可 | |
* | |
* <pre>{@code | |
* // fail-over校验器(出错不退出而继续) | |
* private static final Validator FAIL_OVER_VALIDATOR = buildValidator(false); | |
* }</pre> | |
* | |
* @author yanganyu | |
*/ | |
public class JavaxValidateUtil { | |
/** | |
* fail-fast校验器 (出错即退出) | |
*/ | |
private static final Validator FAIL_FAST_VALIDATOR = buildValidator(true); | |
private static Validator buildValidator(boolean failFast) { | |
return Validation.byProvider(HibernateValidator.class) | |
.configure() | |
.failFast(failFast) | |
.buildValidatorFactory() | |
.getValidator(); | |
} | |
private JavaxValidateUtil() { | |
} | |
/** | |
* fail-fast校验并获取错误信息,即发现一个错误则停止校验 | |
* | |
* @param <T> 目标对象类型 | |
* @param groups 校验器分组 | |
* @param target 校验目标对象 | |
* @return null if has no error, or else return just one error message | |
*/ | |
public static <T> String failFastValidateAndGet(T target, Class<?>... groups) { | |
Objects.requireNonNull(target, "target can not be null"); | |
Set<ConstraintViolation<T>> constraintViolations = FAIL_FAST_VALIDATOR.validate(target, groups); | |
// 由于是fail-fast,'constraintViolations.size()'只可能为0或1 | |
if (constraintViolations.size() > 0) { | |
return constraintViolations.iterator().next().getMessage(); | |
} else { | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment