我们在工作中经常需要对字典选项进行定义,如果客户端传来的字典项不符合要求,那么根本无法保存,但是已有的注解并没有字典值的验证,那我们就自己实现一个
一、自定义字典值验证的注解@DictValid
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** @Author:best_liu* @Description:* @Date Create in 9:32 2023/12/1* @Modified By:*/
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DictValidator.class)
public @interface DictValid {String message() default "字典值错误";String dictType() default "";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};
}
二、验证逻辑处理类
import com.mes.common.core.exception.CustomException;
import com.mes.common.core.utils.StringUtils;
import com.mes.common.core.web.result.AjaxResult;
import com.mes.process.domain.DictVo;
import com.mes.process.service.SysDictFeignService;
import com.mes.process.utils.BeanContextUtils;
import com.mes.process.utils.DictUtil;
import org.springframework.stereotype.Component;import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;/*** @Author: best_liu* @Description:* @Date Create in 9:32 2023/12/1* @Modified By:*/
@Component
public class DictValidator implements ConstraintValidator<DictValid, String> {private SysDictFeignService service;private DictValid dictValid;@Overridepublic void initialize(DictValid dictValid) {this.dictValid = dictValid;}@Overridepublic boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {String dictType = dictValid.dictType();service = BeanContextUtils.getBean(SysDictFeignService.class);//获取数据字典AjaxResult resultStatus = service.dictType(dictType);if (resultStatus == null) {throw new CustomException("system服务断开联系");}List<DictVo> resultStatusOptions = DictUtil.ajaxResultToDict(resultStatus);boolean b = false;if(StringUtils.isNotBlank(s)){b = resultStatusOptions.stream().anyMatch(item -> s.equals(item.getDictValue()));}if(b){return true;}else{return false;}}
}
查询数据字典的类自行编写。这里面直接引用了数据字典的springbean。
这里面需要注意的是SysDictFeignService无法通过注解的形式注入,所以需要借助工具对bean进行注入
springboot 在自定义注解中注入bean,解决注入bean为null的问题-CSDN博客