自定义注解与参数验证

bean validation自带的注解验证

  • pom添加依赖

        javax.validation
        validation-api
        1.1.0.Final
    
    
        org.hibernate
        hibernate-validator
        5.4.1.Final
    
      
       javax.el  
       javax.el-api  
       2.2.4  
      
      
       org.glassfish.web  
       javax.el  
       2.2.4  
     
  • model类
public class Student implements Serializable{
    private static final long serialVersionUID = 1L;
    @NotNull(message = "id不能为空")
    private Integer id;
    private String name;
    //省略getter,setter
}
  • 测试
private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
     
    public static  void main(String[] args) {
        Student stu = new Student();
        stu.setId(null);
        stu.setName("Jimmy");
        //调用验证法方法
        validate(stu);
    }
    
    //验证
    public static void validate(T t){
        Validator validator = factory.getValidator();
        Set> constraintViolations = validator.validate(t);
        for(ConstraintViolation constraintViolation : constraintViolations) {
             System.out.println(constraintViolation.getMessage());
        }
    }
  • 输出
id不能为空

自定义注解验证

  • 注解
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target( {ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CheckCaseValidator.class)//注解实现类
@Documented
public @interface CheckCase {

     String message() default " ";
     
     Class[] groups() default {};
    
     Class[] payload() default {};
    
     String value();
}
  • 注解实现
/**
 * 自定义注解验证
 * @author zhoucheng
 *
 */
public class CheckCaseValidator implements ConstraintValidator {
    private String str;//对应CheckCase注解中的value类型
    
    @Override
    public void initialize(CheckCase constraintAnnotation) {
        this.str = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(value == null){
            return true;
        }
        System.out.println("str-"+str);//str即为声明的注解值Jimmy
        System.out.println(value.toString()+"====");//value即为传入的参数值,此处是传入的name的值Lucy
        if(str.equals(value.toString())){
            System.out.println("-----------true");
            return true;
        }
        return false;
    }
}
  • model类加上自定义注解
@CheckCase(value = "Jimmy",message="名字不能为Jimmy")
private String name;
  • 测试
stu.setName("Lucy");//名字设置为Lucy
输出:
str-Jimmy
value--Lucy
id不能为空

stu.setName("Jimmy");//名字设置为Jimmy
输出:
str-Jimmy
value--Jimmy
-----------true
id不能为空
名字不能为Jimmy

你可能感兴趣的:(自定义注解与参数验证)