mirror of
https://github.com/continew-org/continew-starter.git
synced 2025-09-09 20:57:23 +08:00
feat(core): 新增 JSR 303 校验方法
This commit is contained in:
@@ -23,6 +23,13 @@
|
|||||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Hibernate Validator -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hibernate.validator</groupId>
|
||||||
|
<artifactId>hibernate-validator</artifactId>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- 第三方封装 Ip2region(离线 IP 数据管理框架和定位库,支持亿级别的数据段,10 微秒级别的查询性能,提供了许多主流编程语言的 xdb 数据管理引擎的实现) -->
|
<!-- 第三方封装 Ip2region(离线 IP 数据管理框架和定位库,支持亿级别的数据段,10 微秒级别的查询性能,提供了许多主流编程语言的 xdb 数据管理引擎的实现) -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.dreamlu</groupId>
|
<groupId>net.dreamlu</groupId>
|
||||||
|
@@ -16,9 +16,14 @@
|
|||||||
|
|
||||||
package top.continew.starter.core.util.validate;
|
package top.continew.starter.core.util.validate;
|
||||||
|
|
||||||
|
import cn.hutool.core.collection.CollUtil;
|
||||||
import cn.hutool.core.text.CharSequenceUtil;
|
import cn.hutool.core.text.CharSequenceUtil;
|
||||||
|
import cn.hutool.core.util.ReflectUtil;
|
||||||
|
import cn.hutool.extra.spring.SpringUtil;
|
||||||
|
import jakarta.validation.ConstraintViolation;
|
||||||
import top.continew.starter.core.exception.BadRequestException;
|
import top.continew.starter.core.exception.BadRequestException;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
import java.util.function.BooleanSupplier;
|
import java.util.function.BooleanSupplier;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -173,4 +178,21 @@ public class ValidationUtils extends Validator {
|
|||||||
public static void throwIf(BooleanSupplier conditionSupplier, String template, Object... params) {
|
public static void throwIf(BooleanSupplier conditionSupplier, String template, Object... params) {
|
||||||
throwIf(conditionSupplier, CharSequenceUtil.format(template, params), EXCEPTION_TYPE);
|
throwIf(conditionSupplier, CharSequenceUtil.format(template, params), EXCEPTION_TYPE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JSR 303 校验
|
||||||
|
*
|
||||||
|
* @param obj 被校验对象
|
||||||
|
* @param groups 分组
|
||||||
|
*/
|
||||||
|
public static void validate(Object obj, Class<?>... groups) {
|
||||||
|
jakarta.validation.Validator validator = SpringUtil.getBean(jakarta.validation.Validator.class);
|
||||||
|
Set<ConstraintViolation<Object>> violations = validator.validate(obj, groups);
|
||||||
|
if (CollUtil.isEmpty(violations)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw ReflectUtil.newInstance(EXCEPTION_TYPE, violations.stream()
|
||||||
|
.map(ConstraintViolation::getMessage)
|
||||||
|
.findFirst());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user