废话不多说,直接上代码
Controller层
public Result<Void> save(@Valid @RequestBody GameResult gameResult){
(gameResult);
return ();
}
入参
public class GameResult{
@ApiModuleProperties("用户ID")
private String userId;
@Enum(value = , message = "游戏结果类型错误!1-胜利;0-失败;-1-逃跑")
@ApiModuleProperties("游戏结果")
private Integer result;
}
自定义Enum注解
@Target(FIELD)
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = )
public @interface Enum {
String DEFAULT_MESSAGE = "不在指定枚举值范围内\n";
String message() default DEFAULT_MESSAGE;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<?> value();
String enumMethod() default "getKey";
}
校验类
@Slf4j
public class EnumValidator implements ConstraintValidator<Enum, Integer>{
private Set<Integer> set = new HashSet<>();
@Override
public void initialize(Enum constraintAnnotation){
if(null == constraintAnnotation){
return;
}
Class<?> clazz = ();
String methodName = ();
if(()){
Method getCode;
Object[] objs = ();
try{
getCode = (methodName);
if(null == getCode){
throw new RuntimeException("enum method can not be null, methodName:" + methodName);
}
for(Object obj : objs){
Integer code = (Integer)(obj);
(code);
}
}catch(Exception e){
("EnumValitor error", e);
throw new RuntimeException(e);
}
}
}
}
枚举类
public enum GameResultEnum{
WIN(1),
LOSE(0),
RUN_AWAY(-1);
private Integer key;
GameResultEnum(Integer key){
= key;
}
public Integer getKey(){
return key;
}
}
目前这套代码只支持整数类型枚举值,如果是其他类型的枚举值需要调整一下,只是给各位大佬提供一个思路。
以上。