参考
方案1
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.5</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
测试类- BatchParam
package com.sharding.demo.DTO;
import cn.hutool.extra.validation.ValidationUtil;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import javax.validation.ConstraintViolation;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;
import java.util.Set;
import java.util.stream.Collectors;
@Data
public class BatchParam {
@NotNull(message = "天数不能为空")
private Integer day;
@NotBlank(message = "来源系统不能为空")
private String sourceSystem;
/**
* 参数合法性校验
*
* @return 合法返回验证通过,否则返回错误信息
*/
public String validParams() {
Set<ConstraintViolation<BatchParam>> errorSet = ValidationUtil.validate(this, Default.class);
if (!CollectionUtils.isEmpty(errorSet)) {
return errorSet.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
}
return "验证通过";
}
public static void main(String[] args) {
BatchParam batchParam = new BatchParam();
System.out.println(batchParam.validParams());
System.out.println("-----------");
batchParam.setDay(1);
System.out.println(batchParam.validParams());
System.out.println("-----------");
batchParam.setSourceSystem("mysql");
System.out.println(batchParam.validParams());
}
}
测试结果
11:55:31.129 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 6.0.13.Final
来源系统不能为空;天数不能为空
-----------
来源系统不能为空
-----------
验证通过
错误-Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
一开始只引用了 javax.validation 包
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
执行报下面的错误
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.sharding.demo.DTO.BatchParam.validParams(BatchParam.java:27)
at com.sharding.demo.DTO.BatchParam.main(BatchParam.java:37)
Caused by: javax.validation.NoProviderFoundException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:291)
at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:103)
at cn.hutool.extra.validation.ValidationUtil.<clinit>(ValidationUtil.java:27)
... 2 more
进程已结束,退出代码为 1
加入了下面两个包,执行正常
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
</dependency>
方案2
校验工具类-ValidationUtils
package com.sharding.demo.utils;
import org.apache.commons.collections4.CollectionUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class ValidationUtils {
private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
public static <T> List<String> validate(T obj){
List<String> resultList = new ArrayList<>();
Set<ConstraintViolation<T>> validateSet = VALIDATOR.validate(obj);
if(CollectionUtils.isEmpty(validateSet)){
return resultList;
}
for(ConstraintViolation<T> cs:validateSet){
resultList.add(cs.getMessage());
}
return resultList;
}
}
测试类-BatchParam
package com.sharding.demo.DTO;
import cn.hutool.extra.validation.ValidationUtil;
import com.sharding.demo.utils.ValidationUtils;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import javax.validation.ConstraintViolation;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Data
public class BatchParam {
@NotNull(message = "天数不能为空")
private Integer day;
@NotBlank(message = "来源系统不能为空")
private String sourceSystem;
}
测试结果
public static void main(String[] args) {
BatchParam batchParam = new BatchParam();
List<String> errorMsg = ValidationUtils.validate(batchParam);
if (CollectionUtils.isNotEmpty(errorMsg)) {
System.out.println(errorMsg);
}
System.out.println("-----------");
batchParam.setDay(1);
errorMsg = ValidationUtils.validate(batchParam);
if (CollectionUtils.isNotEmpty(errorMsg)) {
System.out.println(errorMsg);
}
System.out.println("-----------");
batchParam.setSourceSystem("mysql");
errorMsg = ValidationUtils.validate(batchParam);
if (CollectionUtils.isNotEmpty(errorMsg)) {
System.out.println(errorMsg);
}
}
输出
[来源系统不能为空, 天数不能为空]
-----------
[来源系统不能为空]
-----------