jsr303,jsr 349自定义注解验证实现
以下为验证发布状态是否为以下字段
@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"})
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。