DataSize 验证的注解

Annotation for DataSize validation

是否有可用于 DataSize 字段的标准验证器注释?

类似于 javax @Min@Max,或 Hibernate@DurationMin@DurationMax

对于 class DataSize,没有标准验证器,因此您应该实现自己的验证器。但这很容易:)

注释界面:

import org.springframework.util.unit.DataUnit;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Documented
@Constraint(validatedBy = DataSizeMaxValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSizeMax {

    String message() default "must be less than or equal to {value} {unit}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    long value();

    DataUnit unit();
}

验证者:

import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Component
public class DataSizeMaxValidator implements ConstraintValidator<DataSizeMax, DataSize> {
    private DataSize dataSizeMax;

    @Override
    public void initialize(DataSizeMax dataSizeMax) {
        this.dataSizeMax = DataSize.of(dataSizeMax.value(), dataSizeMax.unit());
    }

    @Override
    public boolean isValid(DataSize value, ConstraintValidatorContext context) {
        return dataSizeMax.compareTo(value) >= 0;
    }
}

就是这样。然后在此处使用此注释:

import pizza.nikiforov.validators.DataSizeMax;
import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;

public class Data {

    @DataSizeMax(value = 15L, unit = DataUnit.MEGABYTES)
    private DataSize dataSize;

    // other fields
    // constructors, getters and setters
}