基于@Valid⾃定义校验,校验参数⼤于0定义注解
在这⾥插⼊代码⽚
import der.annotation.validator.NotLessThanZeroValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy ={NotLessThanZeroValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotLessThanZero {
String message();
Class<?>[]groups()default{};
Class<? extends Payload>[]payload()default{};
}
定义注解实现
import der.annotation.NotLessThanZero;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class NotLessThanZeroValidator implements ConstraintValidator<NotLessThanZero, Object>{
@Override
public boolean isValid(Object value, ConstraintValidatorContext context){
if(null == value){
return true;
}
if(value instanceof Number){
if(((Number) value).intValue()>0){
return true;
}
}
return fal;
}
}
使⽤
@Data
@Accessors(chain =true)
@Valid
public class AddOrderItemFeeDTO {
@NotBlank(message ="订单号不能为空")
private String orderId;
@NotBlank(message ="费⽤项不能为空")
private String feeItem;
@NotNull(message ="费⽤项不能为空")
@NotLessThanZero(message ="费⽤项⾦额必须⼤于0") private Double amount;
private String remarks;
}