通过Spring Validation校验配置

一、内置注解校验

  1. 新建Properties配置类ApplicationProperties;
  2. 添加@Validated注解;
  3. 需要校验的字段加上内置注解,例如@NotBlank注解。

    1. @Data
    2. @Component
    3. @Validated
    4. @ConfigurationProperties(prefix = "xxx.application")
    5. public class ApplicationProperties {
    6. /**
    7. * application name
    8. */
    9. @NotBlank(message = "xxx.application.name can not be blank")
    10. private String name;
    11. }

    二、自定义校验规则

  4. 创建ConfigurationPropertiesValidator类,并实现Validator接口;

    1. public class ConfigurationPropertiesValidator implements Validator {
    2. @Override
    3. public boolean supports(Class<?> clazz) {
    4. Set<Class<?>> classSet = new HashSet<>();
    5. classSet.add(ImProperties.class);
    6. classSet.add(VodProperties.class);
    7. return classSet.contains(clazz);
    8. }
    9. @Override
    10. public void validate(Object target, Errors errors) {
    11. if (target instanceof ImProperties) {
    12. ImProperties imProperties = (ImProperties) target;
    13. if (imProperties.isEnableIm()) {
    14. if (imProperties.getSdkAppId() == null) {
    15. errors.rejectValue("sdk-app-id", "null",
    16. "xxx.enable-im equals true, xxx.im.sdk-app-id can not be null");
    17. }
    18. if (StringUtils.isBlank(imProperties.getAppKey())) {
    19. errors.rejectValue("app-key", "blank",
    20. "xxx.im.enable-im equals true, xxx.im.app-key can not be blank");
    21. }
    22. }
    23. } else if (target instanceof VodProperties) {
    24. VodProperties vodProperties = (VodProperties) target;
    25. if (vodProperties.isEnableAutoTranscode()) {
    26. if (vodProperties.getTranscodeDefinition() == null) {
    27. errors.rejectValue("transcode-definition", "null",
    28. "xxx.vod.enable-auto-transcode equals true, xxx.vod.transcode-definition can not be null");
    29. }
    30. }
    31. if (vodProperties.isEnableWatermark()) {
    32. if (vodProperties.getWatermarkDefinition() == null) {
    33. errors.rejectValue("watermark-definition", "null",
    34. "xxx.vod.enable-watermark equals true, xxx.vod.watermark-definition can not be null");
    35. }
    36. }
    37. if (vodProperties.isEnableAutoAiRecognition()) {
    38. if (vodProperties.getAiRecognitionDefinition() == null) {
    39. errors.rejectValue("ai-recognition-definition", "null",
    40. "xxx.vod.enable-auto-ai-recognition equals true, xxx.vod.ai-recognition-definition can not be null");
    41. }
    42. }
    43. }
    44. }
    45. }
  5. 向容器中注册Bean,且Bean的name必须是configurationPropertiesValidator,否则无法校验。

    @Bean
    public ConfigurationPropertiesValidator configurationPropertiesValidator() {
     return new ConfigurationPropertiesValidator();
    }