参数校验
This commit is contained in:
@ -0,0 +1,28 @@
|
||||
package com.greenorange.promotion.annotation;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
import java.util.Arrays;
|
||||
|
||||
// 枚举校验器
|
||||
public class EnumValidator implements ConstraintValidator<EnumValue, String> {
|
||||
|
||||
private EnumValue enumValue;
|
||||
|
||||
@Override
|
||||
public void initialize(EnumValue constraintAnnotation) {
|
||||
this.enumValue = constraintAnnotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String value, ConstraintValidatorContext context) {
|
||||
if (value == null) {
|
||||
return true; // 如果值为 null,跳过校验,可以用 @NotNull 另行校验
|
||||
}
|
||||
|
||||
// 获取枚举类
|
||||
Class<? extends Enum<?>> enumClass = enumValue.enumClass();
|
||||
return Arrays.stream(enumClass.getEnumConstants())
|
||||
.anyMatch(enumConstant -> enumConstant.name().equals(value));
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.greenorange.promotion.annotation;
|
||||
|
||||
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 = EnumValidator.class)
|
||||
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface EnumValue {
|
||||
String message() default "无效的用户角色"; // 错误信息
|
||||
Class<?>[] groups() default {}; // 组别
|
||||
Class<? extends Payload>[] payload() default {}; // 负载
|
||||
Class<? extends Enum<?>> enumClass(); // 枚举类类型
|
||||
}
|
Reference in New Issue
Block a user