gpt4 book ai didi

java - DataSize 验证的注释

转载 作者:行者123 更新时间:2023-12-02 08:55:20 26 4
gpt4 key购买 nike

是否有任何标准 validator 注释可以用于 DataSize领域?

类似于 javax @Min@MaxHibernate@DurationMin@DurationMax

最佳答案

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

注解接口(interface):

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();
}

validator :

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
}

关于java - DataSize 验证的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60526871/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com