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;

 

發佈了15 篇原創文章 · 獲贊 4 · 訪問量 3660
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章