通过Spring Validation校验配置
一、内置注解校验
- 新建Properties配置类ApplicationProperties;
- 添加@Validated注解;
需要校验的字段加上内置注解,例如@NotBlank注解。
@Data@Component@Validated@ConfigurationProperties(prefix = "xxx.application")public class ApplicationProperties {/*** application name*/@NotBlank(message = "xxx.application.name can not be blank")private String name;}
二、自定义校验规则
创建ConfigurationPropertiesValidator类,并实现Validator接口;
public class ConfigurationPropertiesValidator implements Validator {@Overridepublic boolean supports(Class<?> clazz) {Set<Class<?>> classSet = new HashSet<>();classSet.add(ImProperties.class);classSet.add(VodProperties.class);return classSet.contains(clazz);}@Overridepublic void validate(Object target, Errors errors) {if (target instanceof ImProperties) {ImProperties imProperties = (ImProperties) target;if (imProperties.isEnableIm()) {if (imProperties.getSdkAppId() == null) {errors.rejectValue("sdk-app-id", "null","xxx.enable-im equals true, xxx.im.sdk-app-id can not be null");}if (StringUtils.isBlank(imProperties.getAppKey())) {errors.rejectValue("app-key", "blank","xxx.im.enable-im equals true, xxx.im.app-key can not be blank");}}} else if (target instanceof VodProperties) {VodProperties vodProperties = (VodProperties) target;if (vodProperties.isEnableAutoTranscode()) {if (vodProperties.getTranscodeDefinition() == null) {errors.rejectValue("transcode-definition", "null","xxx.vod.enable-auto-transcode equals true, xxx.vod.transcode-definition can not be null");}}if (vodProperties.isEnableWatermark()) {if (vodProperties.getWatermarkDefinition() == null) {errors.rejectValue("watermark-definition", "null","xxx.vod.enable-watermark equals true, xxx.vod.watermark-definition can not be null");}}if (vodProperties.isEnableAutoAiRecognition()) {if (vodProperties.getAiRecognitionDefinition() == null) {errors.rejectValue("ai-recognition-definition", "null","xxx.vod.enable-auto-ai-recognition equals true, xxx.vod.ai-recognition-definition can not be null");}}}}}
向容器中注册Bean,且Bean的name必须是configurationPropertiesValidator,否则无法校验。
@Bean public ConfigurationPropertiesValidator configurationPropertiesValidator() { return new ConfigurationPropertiesValidator(); }
