BigDecimal精度校验器

1.定义校验器


/**
 * @author tlj
 * @date 2019/7/9
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Constraint(validatedBy = DecimalValidator.EnumValidatorHandle.class)
public @interface DecimalValidator {
    int maxScale();

    String message() default "精度错误";
    Class<?>[] groups()    default {};

    Class<? extends Payload>[] payload() default {};
    /**
     * @author tlj
     * @date 2019/7/9
     */
    @Slf4j
    class EnumValidatorHandle implements ConstraintValidator<DecimalValidator, Object>, Annotation {
        private int maxScale;

        @Override
        public void initialize(DecimalValidator decimalValidator) {
            maxScale = decimalValidator.maxScale();
        }


        @Override
        public Class<? extends Annotation> annotationType() {
            return null;
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if(value==null){
                return true;
            }
            if (value instanceof BigDecimal) {
                BigDecimal bigDecimal = (BigDecimal)value;
                return  bigDecimal.scale()<=maxScale;
            }
            throw new PldDetailException(ProductResultCodeEnum.PRODUCT_NEED_PARAM_EXCEPTION,"DecimalValidator只能作用在BigDecimal类型上");
        }
    }

}

2.使用

    @ApiModelProperty(value = "产品金额", required = true)
    @NotNull(message = "产品金额不能为空")
    @DecimalValidator(maxScale = 2,message = "产品金额最大精度为2")
    @Min(value = 0, message = "产品金额最小值不能小于0")
    private BigDecimal amt;
发布了14 篇原创文章 · 获赞 4 · 访问量 2735

猜你喜欢

转载自blog.csdn.net/www_tlj/article/details/103953853
今日推荐