以下为验证发布状态是否为以下字段
@Documented @Constraint(validatedBy = {PublishStatusValidator.class }) @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @NotBlank /** * Verify the status contains value * status default values {"pending","publish","invalid"}. */ public @interface PublishStatus { String[] status() default {"fabu1","fabu2","fabu3"}; String message() default "状态值不匹配,值必须是{status}中的值"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; /** * Defines several {@code @Length} annotations on the same element. */ @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented public @interface List { PublishStatus[] value(); } }
上面我们还加了@NotBank,表示不能为空,当然这里看自己业务需求了。
继承与ConstraintValidator实现验证
public class PublishStatusValidator implements ConstraintValidator<PublishStatus, CharSequence> { private CharSequence[] statusStr; @Override public void initialize(PublishStatus constraintAnnotation) { this.statusStr = constraintAnnotation.status(); } @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context) { return Arrays.asList(statusStr).contains(value); } }
使用方法
@PublishStatus @PublishStatus(status = {"a","b","c"})
时间: 2024-10-17 22:33:50