如何自定义注解?

第一步:通过开发工具创建一个注解@AgeBetween

其中,@Target是元注解,就是用在注解上的注解

复制代码
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = StudentAgeValidator.class)
public @interface AgeBetween {
String message() default “Not in line with the student’s age”;
int min() default 0;
int max() default 30;
Class[] groups() default {};
Class[] payload() default {};
}
复制代码

第二步:设置注解的判断方式

复制代码
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class StudentAgeValidator implements ConstraintValidator {
private Integer min;
private Integer max;
@Override
public void initialize(AgeBetween ageBetween) {
this.min = ageBetween.min();
this.max = ageBetween.max();
}
@Override
public boolean isValid(Integer age, ConstraintValidatorContext constraintValidatorContext) {
return age > min && age < max;
}
}
复制代码

第三步:在需要限制的属性上加上注解

复制代码
import javax.validation.constraints.NotNull;

public class Student {
@NotNull
private String name;

@AgeBetween(min=10,max = 20)
private Integer age;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

}
复制代码

你可能感兴趣的:(java)