我避免了double
和float
类型,并实现了一个自定义验证器,它可以BigDecimal
根据精度和比例来验证一个值。
约束描述符。
package constraintdescriptor;
import constraintvalidator.BigDecimalRangeValidator;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = BigDecimalRangeValidator.class)
@Documented
public @interface BigDecimalRange {
public String message() default "{java.math.BigDecimal.range.error}";
public Class<?>[] groups() default {};
public Class<? extends Payload>[] payload() default {};
long minPrecision() default Long.MIN_VALUE;
long maxPrecision() default Long.MAX_VALUE;
int scale() default 0;
}
约束验证器。
package constraintvalidator;
import constraintdescriptor.BigDecimalRange;
import java.math.BigDecimal;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public final class BigDecimalRangeValidator implements ConstraintValidator<BigDecimalRange, Object> {
private long maxPrecision;
private long minPrecision;
private int scale;
@Override
public void initialize(final BigDecimalRange bigDecimalRange) {
maxPrecision = bigDecimalRange.maxPrecision();
minPrecision = bigDecimalRange.minPrecision();
scale = bigDecimalRange.scale();
}
@Override
public boolean isValid(final Object object, final ConstraintValidatorContext cvc) {
boolean isValid = false;
if (object == null) { // This should be validated by the not null validator (@NotNull).
isValid = true;
} else if (object instanceof BigDecimal) {
BigDecimal bigDecimal = new BigDecimal(object.toString());
int actualPrecision = bigDecimal.precision();
int actualScale = bigDecimal.scale();
isValid = actualPrecision >= minPrecision && actualPrecision <= maxPrecision && actualScale <= scale;
if (!isValid) {
cvc.disableDefaultConstraintViolation();
cvc.buildConstraintViolationWithTemplate("Precision expected (minimun : " + minPrecision + ", maximum : " + maxPrecision + "). Maximum scale expected : " + scale + ". Found precision : " + actualPrecision + ", scale : " + actualScale).addConstraintViolation();
}
}
return isValid;
}
}
这也可以在需要时扩展到其他类型。
最后在 bean 中,类型的属性BigDecimal
可以通过@BigDecimalRange
注解进行如下注解。
package validatorbeans;
public final class WeightBean {
@BigDecimalRange(minPrecision = 1, maxPrecision = 33, scale = 2, groups = {ValidationGroup.class}, message = "The precision and the scale should be less than or equal to 35 and 2 respectively.")
private BigDecimal txtWeight; // Getter and setter.
public interface ValidationGroup {}
}