日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

SpringBoot自定義Validated枚舉校驗(yàn)器

作者:weixin_44953227 更新時(shí)間: 2022-04-09 編程語言

目錄

    • 1. 自定義注解
    • 2. 注解校驗(yàn)器
    • 3. 枚舉
    • 4. 使用注解
    • 校驗(yàn)深層次的實(shí)體

前言:枚舉校驗(yàn)器主要為了規(guī)范和統(tǒng)一使用固定的字符或者數(shù)字值

SpringBoot 版本 2.xx

依賴,一般使用添加了 spring-boot-starter-web 這個(gè)依賴就行了,他里面包含了數(shù)據(jù)校驗(yàn)的依賴,但還是在這里指明一下具體的依賴。


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-validationartifactId>
dependency>


1. 自定義注解

默認(rèn)校驗(yàn) getCode 方法獲取的值。如果要校驗(yàn)枚舉的其他字段,直接指定get方法。

package com.pro.annotation;

import com.pro.annotation.EnumValidtor;

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

/**
 * 校驗(yàn)入?yún)⑹欠駷橹付╡num的值的注解
 */
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {EnumValidtor.class})
@Documented
public @interface EnumValid {

    String message() default "";

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

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

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

    String vaildField() default "getCode";
}


2. 注解校驗(yàn)器

package com.pro.annotation;

import com.pro.annotation.EnumValid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 校驗(yàn)入?yún)⑹欠駷橹付╡num的值的實(shí)現(xiàn)方法
 */
public class EnumValidtor implements ConstraintValidator<EnumValid, Object> {

    String vaildField;
    Class<?>[] cls; //枚舉類

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        cls = constraintAnnotation.target();
        vaildField = constraintAnnotation.vaildField();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value != null && value.toString().length() > 0 && cls.length > 0) {
            for (Class<?> cl : cls
            ) {
                try {
                    if (cl.isEnum()) {
                        //枚舉類驗(yàn)證
                        Object[] objs = cl.getEnumConstants();
                        Method method = cl.getMethod("name");
                        for (Object obj : objs) {
                            Object code = method.invoke(obj, null);
                            if (value.equals(code.toString())) {
                                return true;
                            }
                        }
                        Method codeMethod = cl.getMethod(vaildField);
                        for (Object obj : objs) {
                            Object code = codeMethod.invoke(obj, null);
                            if (value.toString().equals(code.toString())) {
                                return true;
                            }
                        }
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return true;
        }
        return false;
    }

}


3. 枚舉

package com.pro.enums;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public enum GenderEnum {

    /**
     * 男
     */
    MALE("MALE", "男"),

    /**
     * 女
     */
    FEMALE("FEMALE", "女"),
    ;

    private String code;

    private String name;

    GenderEnum(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public String getName() {
        return name;
    }

    public static List<Map<String, Object>> toList() {
        List<Map<String, Object>> result = new ArrayList<>();
        for (GenderEnum e : GenderEnum.values()) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", e.getCode());
            map.put("value", e.getName());
            result.add(map);
        }
        return result;
    }

    public static String getNameByCode(String code) {
        for (GenderEnum value : values()) {
            if (value.code.equals(code)) {
                return value.name;
            }
        }
        return "未知";
    }
}



4. 使用注解

public class TestDTO {

	// 默認(rèn)校驗(yàn) getCode 方法獲取的值
	@NotBlank(message = "性別不能為空")
    @EnumValid(target = GenderEnum.class, message = "性別輸入錯(cuò)誤")
    private String gender;
    
    // 如果想校驗(yàn)枚舉中其他的值, 直接指定 vaildField 方法的值即可, 下面是例子
    @NotBlank(message = "性別不能為空")
    @EnumValid(target = GenderEnum.class, vaildField = "getName", message = "性別輸入錯(cuò)誤")
    private String gender2;

	// 此處省略 get、set
}


校驗(yàn)深層次的實(shí)體

這里說一句在 SpringBoot 中默認(rèn)只會(huì)校驗(yàn)第一層實(shí)體類,如果想校驗(yàn)實(shí)體字段中的實(shí)體,需要在字段上加 @Valid 注解。

比如想校驗(yàn) AddDTO 這個(gè)實(shí)體

public class TestDTO {

	// 默認(rèn)校驗(yàn) getCode 方法獲取的值
	@NotBlank(message = "性別不能為空")
    @EnumValid(target = GenderEnum.class, message = "性別輸入錯(cuò)誤")
    private String gender;

	/**
     * 比如想讓 AddDTO 中的字段上的注解校驗(yàn)也生效就必須加上 @Valid 這個(gè)注解
     */
    @Valid
    private List<AddDTO> addList;

	// 此處省略 get、set
}

使用校驗(yàn)

	@PostMapping("/update")
    public Result updateAdverseRelation(@Validated @RequestBody TestDTO dto) {
    
    }

原文鏈接:https://blog.csdn.net/weixin_44953227/article/details/121841128

欄目分類
最近更新