1、自定义注解State
message、groups、payload
package com.zhang.anno;
import com.zhang.validartion.StateValidation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* @program: big_event
* @description: TODO
* @author: Mr.Zhang
* @create: 2024-04-06 14:18
**/
@Documented //元注解
@Retention(RUNTIME) //元注解
@Target({FIELD}) //元注解
@Constraint(
validatedBy = {StateValidation.class}//指定提供校验器规则的类
)
public @interface State {
//提供校验失败后的提示消息
String message() default "state参数的值只能是已发布或者草稿";
//指定分组
Class<?>[] groups() default {};
//负载 获取到state注解的附加信息
Class<? extends Payload>[] payload() default {};
}
2、自定义校验数据的类StateValidation
package com.zhang.validartion;
import com.zhang.anno.State;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
/**
* @program: big_event
* @description: TODO
* @author: Mr.Zhang
* @create: 2024-04-06 14:25
**/
//public class StateValidation implements ConstraintValidator<给哪个注解提供检验规则,检验的数据类型> {
//
//}
public class StateValidation implements ConstraintValidator<State,String> {
/**
*
* @param value 将来要检验的数据
* @param context
* @return 如果返回false,则表示校验失败,如果返回true,则表示校验成功
*/
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
//提供校验规则
if (value == null) {
return false;
}
if ("已发布".equals(value) || "草稿".equals(value)) {
return true;
}
//如果校验失败,则提供提示信息
return false;
}
}
3、在需要校验的地方使用自定义注解
![](https://i-blog.csdnimg.cn/blog_migrate/768b0950cbf58b305bfd58421677f7b3.png)