新增FloatRange注解
自定义注解,名称随便命名,其中Constraint元注解是必须的,指定验证的ConstraintValidator
package com.genergy.cloud.common.validated;
import org.hibernate.validator.constraints.Range;
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.constraintvalidation.SupportedValidationTarget;
import javax.validation.constraintvalidation.ValidationTarget;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Constraint(validatedBy = FloatRangeValidator.class)
@SupportedValidationTarget(ValidationTarget.ANNOTATED_ELEMENT)
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
public @interface FloatRange {
float min() default 0;
@Range
float max() default Short.MAX_VALUE;
String message() default "{org.hibernate.validator.constraints.Range.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
- validatedBy:验证器,验证时会调用这个类
- min():最小值
- max():最大值
- message:验证不通过时,抛出的提示信息,"{org.hibernate.validator.constraints.Range.message}" 从com.genergy.cloud.common.validated.ValidationMessages.properties属性文件中获取值,本地配置在resource文件夹下新增一个同名文件
实现javax.validation.ConstraintValidator接口
在该接口中实现验证值的逻辑
package com.genergy.cloud.common.validated;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class FloatRangeValidator implements ConstraintValidator<FloatRange, Float> {
private Float min;
private Float max;
/**
* 初始化验证值
*
* @param floatRange 验证注解
*/
@Override
public void initialize(FloatRange floatRange) {
this.min = floatRange.min();
this.max = floatRange.max();
}
/**
*
* @param value 加了{@link FloatRange}属性的值
* @param context 验证上下文
* @return true 验证通过,false 验证失败
*/
@Override
public boolean isValid(Float value, ConstraintValidatorContext context) {
// 空值放行,只对非空值做验证,不要在这里处理null的情况,确保职责单一
if ( value == null ) {
return true;
}
return Float.compare(min, value) <= 0 && Float.compare(max, value) >= 0 ;
}
}