SpringBoot-通用参数校验

2024年04月11日 11:57 · 阅读(238) ·

参考

SpringBoot-jsr303 参数校验

Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath

方案1

pom.xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.projectlombok</groupId>
  8. <artifactId>lombok</artifactId>
  9. <optional>true</optional>
  10. </dependency>
  11. <dependency>
  12. <groupId>cn.hutool</groupId>
  13. <artifactId>hutool-all</artifactId>
  14. <version>5.7.5</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>javax.validation</groupId>
  18. <artifactId>validation-api</artifactId>
  19. <version>2.0.1.Final</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.hibernate.validator</groupId>
  23. <artifactId>hibernate-validator</artifactId>
  24. <version>6.0.13.Final</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.glassfish</groupId>
  28. <artifactId>javax.el</artifactId>
  29. <version>3.0.0</version>
  30. </dependency>
  31. </dependencies>

测试类- BatchParam

  1. package com.sharding.demo.DTO;
  2. import cn.hutool.extra.validation.ValidationUtil;
  3. import lombok.Data;
  4. import org.apache.commons.collections4.CollectionUtils;
  5. import javax.validation.ConstraintViolation;
  6. import javax.validation.constraints.NotBlank;
  7. import javax.validation.constraints.NotNull;
  8. import javax.validation.groups.Default;
  9. import java.util.Set;
  10. import java.util.stream.Collectors;
  11. @Data
  12. public class BatchParam {
  13. @NotNull(message = "天数不能为空")
  14. private Integer day;
  15. @NotBlank(message = "来源系统不能为空")
  16. private String sourceSystem;
  17. /**
  18. * 参数合法性校验
  19. *
  20. * @return 合法返回验证通过,否则返回错误信息
  21. */
  22. public String validParams() {
  23. Set<ConstraintViolation<BatchParam>> errorSet = ValidationUtil.validate(this, Default.class);
  24. if (!CollectionUtils.isEmpty(errorSet)) {
  25. return errorSet.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
  26. }
  27. return "验证通过";
  28. }
  29. public static void main(String[] args) {
  30. BatchParam batchParam = new BatchParam();
  31. System.out.println(batchParam.validParams());
  32. System.out.println("-----------");
  33. batchParam.setDay(1);
  34. System.out.println(batchParam.validParams());
  35. System.out.println("-----------");
  36. batchParam.setSourceSystem("mysql");
  37. System.out.println(batchParam.validParams());
  38. }
  39. }

测试结果

  1. 11:55:31.129 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 6.0.13.Final
  2. 来源系统不能为空;天数不能为空
  3. -----------
  4. 来源系统不能为空
  5. -----------
  6. 验证通过

错误-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 包

  1. <dependency>
  2. <groupId>javax.validation</groupId>
  3. <artifactId>validation-api</artifactId>
  4. <version>2.0.1.Final</version>
  5. </dependency>

执行报下面的错误

  1. Exception in thread "main" java.lang.ExceptionInInitializerError
  2. at com.sharding.demo.DTO.BatchParam.validParams(BatchParam.java:27)
  3. at com.sharding.demo.DTO.BatchParam.main(BatchParam.java:37)
  4. 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.
  5. at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:291)
  6. at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:103)
  7. at cn.hutool.extra.validation.ValidationUtil.<clinit>(ValidationUtil.java:27)
  8. ... 2 more
  9. 进程已结束,退出代码为 1

加入了下面两个包,执行正常

  1. <dependency>
  2. <groupId>org.hibernate.validator</groupId>
  3. <artifactId>hibernate-validator</artifactId>
  4. <version>6.0.13.Final</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.glassfish</groupId>
  8. <artifactId>javax.el</artifactId>
  9. <version>3.0.0</version>
  10. </dependency>

方案2

校验工具类-ValidationUtils

  1. package com.sharding.demo.utils;
  2. import org.apache.commons.collections4.CollectionUtils;
  3. import javax.validation.ConstraintViolation;
  4. import javax.validation.Validation;
  5. import javax.validation.Validator;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.Set;
  9. public class ValidationUtils {
  10. private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
  11. public static <T> List<String> validate(T obj){
  12. List<String> resultList = new ArrayList<>();
  13. Set<ConstraintViolation<T>> validateSet = VALIDATOR.validate(obj);
  14. if(CollectionUtils.isEmpty(validateSet)){
  15. return resultList;
  16. }
  17. for(ConstraintViolation<T> cs:validateSet){
  18. resultList.add(cs.getMessage());
  19. }
  20. return resultList;
  21. }
  22. }

测试类-BatchParam

  1. package com.sharding.demo.DTO;
  2. import cn.hutool.extra.validation.ValidationUtil;
  3. import com.sharding.demo.utils.ValidationUtils;
  4. import lombok.Data;
  5. import org.apache.commons.collections4.CollectionUtils;
  6. import javax.validation.ConstraintViolation;
  7. import javax.validation.constraints.NotBlank;
  8. import javax.validation.constraints.NotNull;
  9. import javax.validation.groups.Default;
  10. import java.util.List;
  11. import java.util.Set;
  12. import java.util.stream.Collectors;
  13. @Data
  14. public class BatchParam {
  15. @NotNull(message = "天数不能为空")
  16. private Integer day;
  17. @NotBlank(message = "来源系统不能为空")
  18. private String sourceSystem;
  19. }

测试结果

  1. public static void main(String[] args) {
  2. BatchParam batchParam = new BatchParam();
  3. List<String> errorMsg = ValidationUtils.validate(batchParam);
  4. if (CollectionUtils.isNotEmpty(errorMsg)) {
  5. System.out.println(errorMsg);
  6. }
  7. System.out.println("-----------");
  8. batchParam.setDay(1);
  9. errorMsg = ValidationUtils.validate(batchParam);
  10. if (CollectionUtils.isNotEmpty(errorMsg)) {
  11. System.out.println(errorMsg);
  12. }
  13. System.out.println("-----------");
  14. batchParam.setSourceSystem("mysql");
  15. errorMsg = ValidationUtils.validate(batchParam);
  16. if (CollectionUtils.isNotEmpty(errorMsg)) {
  17. System.out.println(errorMsg);
  18. }
  19. }

输出

  1. [来源系统不能为空, 天数不能为空]
  2. -----------
  3. [来源系统不能为空]
  4. -----------