新建 validator
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValueValidator.Validator.class)
/**
* 枚举校验器
*/
public @interface EnumValueValidator {
String message() default "{EnumValueValidator's value is invalid}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<? extends Enum<?>> enumClass();
class Validator implements ConstraintValidator<EnumValueValidator, Object> {
private Class<? extends Enum<?>> enumClass;
private String enumMethod="isValidName";
@Override
public void initialize(EnumValueValidator enumValue) {
enumClass=enumValue.enumClass();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
if (value == null) {
return Boolean.FALSE;
}
Class<?> valueClass = value.getClass();
try {
Method method = enumClass.getMethod(enumMethod, valueClass);
if (!Boolean.TYPE.equals(method.getReturnType()) && !Boolean.class.equals(method.getReturnType())) {
return Boolean.FALSE;
}
if(!Modifier.isStatic(method.getModifiers())) {
return Boolean.FALSE;
}
Boolean result = (Boolean)method.invoke(null, value);
return result == null ? false : result;
} catch (Exception e) {
e.printStackTrace();
return Boolean.FALSE;
}
}
}
}
对应枚举进行调整
public enum ServerStatusEnum {
NORMAL(0,"正常"),
ABNORMAL(1,"异常"),
LOCK(2,"锁定");
private Integer status;
private String des;
public Integer getStatus() {
return status;
}
public String getDes() {
return des;
}
ServerStatusEnum(Integer status,String des){
this.status = status;
this.des = des;
}
public boolean match(final Integer status) {
return this.getStatus().intValue() == status;
}
/**
* 状态是否合法
* @param status 状态
* @return 是否合法
*/
public static boolean isValidName(final Integer status) {
for (ServerStatusEnum item : values()) {
if (item.getStatus().intValue() == status) {
return true;
}
}
return false;
}
}
具体 DTO 使用
public class BaseServerDTO {
@ApiModelProperty(value = "服务器状态:(默认正常)")
@NotNull(message = "服务器状态不能为空")
@EnumValueValidator(enumClass = ServerStatusEnum.class,message = "当前服务器状态不合法")
private Integer status = 0;
}