如何自定义注解?

第一步:通过开发工具创建一个注解@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<? extends Payload>[] payload() default {};
}

 

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

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class StudentAgeValidator implements ConstraintValidator<AgeBetween,Integer> {
    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;
    }
}

 

posted @ 2021-03-15 14:25  Java精进之路  阅读(620)  评论(0编辑  收藏  举报