这里我们介绍以下自定义的校验器的简单的使用示例

一、包结构和主要文件

二、代码

1.自定义注解文件MyConstraint

package com.knyel.validator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.FIELD})//注解可以标注在什么元素上
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint {
    String message();

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

2.自定义校验逻辑文件MyConstraintValidator

package com.knyel.validator;

import com.knyel.service.HelloKnyel;
import org.springframework.beans.factory.annotation.Autowired;

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


//ConstraintValidator<A,T>
//A参数:表示要验证的注解
//T参数:表示要验证的东西是什么类型
public class MyConstraintValidator implements ConstraintValidator<MyConstraint,Object> {

    @Autowired
    HelloKnyel helloKnyel;

    @Override
    public void initialize (MyConstraint myConstraint){
        //校验器初始化的时候做的一些工作
        System.out.println("myvalidator init");
    }

    /*
    真正的校验逻辑
    Object o :传进来的校验的值
    ConstraintValidatorContext constraintValidatorContext :校验的上下文
     */
    @Override
    public boolean isValid (Object value, ConstraintValidatorContext constraintValidatorContext){
        //处理校验逻辑
        helloKnyel.welcome("knyel");
        System.out.println(value);
        //true代表校验成功,false代表校验失败
        return false;
    }
}

3.在2中isValid方法中调用的校验逻辑业务HelloKnyelImpl及接口

package com.knyel.service;

public interface HelloKnyel {
    String welcome(String name);
}

 

package com.knyel.service.impl;

import com.knyel.service.HelloKnyel;
import org.springframework.stereotype.Service;

@Service
public class HelloKnyelImpl implements HelloKnyel {

    @Override
    public String welcome (String name){
        System.out.println("welcome");
        return "hello knyel";
    }
}

4.待校验的实体

package com.knyel.dto;

import com.fasterxml.jackson.annotation.JsonView;
import com.knyel.validator.MyConstraint;
import org.hibernate.validator.constraints.NotBlank;

import javax.validation.constraints.Past;
import java.util.Date;

public class User {

    public interface UserSimpleView {};
    public interface UserDetailView extends UserSimpleView {};

    private String id;
    @MyConstraint(message = "测试校验器")
    private String username;
    @NotBlank(message="密码不能为空")
    private  String password;
    @Past(message = "生日必须是过去的时间")
    private Date birthday;

    @JsonView(UserSimpleView.class)
    public String getUsername (){
        return username;
    }

    public void setUsername (String username){
        this.username = username;
    }
    @JsonView(UserDetailView.class)
    public String getPassword (){
        return password;
    }

    public void setPassword (String password){
        this.password = password;
    }

    @JsonView(UserSimpleView.class)
    public String getId (){
        return id;
    }
    @JsonView(UserSimpleView.class)
    public void setId (String id){
        this.id = id;
    }

    public Date getBirthday (){
        return birthday;
    }

    public void setBirthday (Date birthday){
        this.birthday = birthday;
    }

    @Override
    public String toString (){
        return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", birthday=" + birthday + '}';
    }
}

5.controller

    @PutMapping("/{id:\\d+}")
    public User update (@Valid @RequestBody User user, BindingResult errors){
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach((ObjectError error) ->{
//                FieldError fieldError=(FieldError) error;
//                String message=fieldError.getField()+":"+fieldError.getDefaultMessage();
                System.out.println(error.getDefaultMessage());
            });
        }
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        System.out.println(user.getBirthday());
        user.setId("1");
        return user;
    }

执行测试用例后

myvalidator init
welcome
knyel
测试校验器
1

 

posted on 2017-11-28 22:13  knyel  阅读(870)  评论(0编辑  收藏  举报