美文网首页JAVA_Spring
SpringBoot 9 自定义注解实现校验

SpringBoot 9 自定义注解实现校验

作者: kason_zhang | 来源:发表于2018-11-03 12:24 被阅读1次

元注解

java.lang.annotation提供了四种元注解,专门注解其他的注解(在自定义注解的时候,需要使用到元注解):
   @Documented –注解是否将包含在JavaDoc中
   @Retention –什么时候使用该注解
   @Target –注解用于什么地方
   @Inherited – 是否允许子类继承该注解

  1.)@Retention– 定义该注解的生命周期
  ●   RetentionPolicy.SOURCE : 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@Override, @SuppressWarnings都属于这类注解。
  ●   RetentionPolicy.CLASS : 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式
  ●   RetentionPolicy.RUNTIME : 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。

  2.)Target – 表示该注解用于什么地方。默认值为任何元素,表示该注解用于什么地方。可用的ElementType参数包括
  ● ElementType.CONSTRUCTOR:用于描述构造器
  ● ElementType.FIELD:成员变量、对象、属性(包括enum实例)
  ● ElementType.LOCAL_VARIABLE:用于描述局部变量
  ● ElementType.METHOD:用于描述方法
  ● ElementType.PACKAGE:用于描述包
  ● ElementType.PARAMETER:用于描述参数
  ● ElementType.TYPE:用于描述类、接口(包括注解类型) 或enum声明

 3.)@Documented–一个简单的Annotations标记注解,表示是否将注解信息添加在java文档中。

 4.)@Inherited – 定义该注释和子类的关系
     @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

SpringBoot 前后端通过注解完成校验参数.

此处假设有个post接口, 传入的是用户UserVo, 其参数是name, id, mobile, 此处来对mobile参数实现手机号码注解校验.

首先定义注解接口:

package com.secondkill.validator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * Created by zhangkai12 on 2018/7/4.
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD})
@Constraint(validatedBy = IsMobileValidator.class)
public @interface IsMobile {

    boolean needsValid() default true;
    Class<?>[] groups() default {};
    String message() default "手机格式不正确";
    Class<? extends Payload>[] payload() default{};
}

其次定义注解校验类即@Constraint(validatedBy = IsMobileValidator.class)指定的类IsMobileValidator

package com.secondkill.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhangkai12 on 2018/7/4.
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean needsValid;
    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        System.out.println("comes to valid mobile number");
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(s);

        return m.matches();
    }

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        this.needsValid = constraintAnnotation.needsValid();
    }
}

之后就是在UserVo中使用这个注解了. UserVo类的内容如下:

package com.secondkill.vo;

import com.secondkill.validator.IsMobile;

import javax.persistence.Entity;

/**
 * Created by zhangkai12 on 2018/7/4.
 */

public class UserVo {
    private String name;
    private int id;
    @IsMobile
    private String mobile;

    public UserVo() {
    }

    public UserVo(String name, int id, String mobile) {
        this.name = name;
        this.id = id;
        this.mobile = mobile;
    }

    public String getName() {
        return name;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getMobile() {
        return mobile;
    }


    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

最终就是Controller中的使用:

@PostMapping("/post")
    @ResponseBody
    public Result<Boolean> postUser(@Valid UserVo userVo) {

        return Result.success(true);
    }

通过postman来测试接口, 如下图


image.png

相关文章

网友评论

    本文标题:SpringBoot 9 自定义注解实现校验

    本文链接:https://www.haomeiwen.com/subject/mooeuftx.html