SpringBoot自定義注解驗證枚舉的實現(xiàn)
業(yè)務(wù)場景:數(shù)據(jù)校驗,需要對枚舉類型的數(shù)據(jù)傳參,進(jìn)行數(shù)據(jù)校驗,不能隨便傳參。
1、引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
2、創(chuàng)建注解類
package com.shier.valid;
import com.shier.validator.EnumValueValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* @author cys
*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValueValidator.class})
public @interface EnumValue {
// 默認(rèn)錯誤消息
String message() default "必須為指定值";
// 字符串類型
String[] strValues() default {};
// 整型
int[] intValues() default {};
// 分組
Class<?>[] groups() default {};
// 負(fù)載
Class<? extends Payload>[] payload() default {};
// 忽略null, 為true時,參數(shù)傳null不檢驗
boolean ignoreNull() default false;
;
// 指定多個時使用
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
EnumValue[] value();
}
}
3、創(chuàng)建自定義檢驗器類
package com.shier.validator;
import com.shier.valid.EnumValue;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
/**
* @author cys
*/
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {
private String[] strValues;
private int[] intValues;
private boolean ignoreNull;
@Override
public void initialize(EnumValue constraintAnnotation) {
this.strValues = constraintAnnotation.strValues();
this.intValues = constraintAnnotation.intValues();
this.ignoreNull = constraintAnnotation.ignoreNull();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
if (Objects.isNull(value) && this.ignoreNull) {
return true;
}
if (value instanceof String) {
for (String s : strValues) {
if (s.equals(value)) {
return true;
}
}
} else if (value instanceof Integer) {
for (Integer s : intValues) {
if (s == value) {
return true;
}
}
}
return false;
}
}
4、創(chuàng)建請求類
package com.shier.controller;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.shier.valid.EnumValue;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.Date;
/**
* @author shier
* @date 2023年01月12日
*/
@Data
public class OrderReq {
private Long orderId;
@EnumValue(intValues = {1,2,3,4}, message = "訂單狀態(tài)必須為指定值,1-新建 2-已支付 3-已完成 4-已取消",ignoreNull = true)
private Integer orderStatus;
/**
* JsonFormat: 可以把日期類型轉(zhuǎn)成指定格式輸出
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
private Date updateTime;
}
5、測試類
package com.shier.controller;
import com.shier.req.OrderReq;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Date;
/**
* @author shier
* @date 2023年01月12日
*/
@RestController
public class TestController {
@GetMapping("/test")
public OrderReq test(@RequestBody @Valid OrderReq orderReq) {
orderReq.setCreateTime(LocalDateTime.now());
orderReq.setUpdateTime(new Date());
return orderReq;
}
}
6、啟動測試


因為在OrderReq類中的orderStatus字段添加了注解規(guī)定值在1、2、3、4。如果傳入其他值會提示異樣, 這里因為沒有統(tǒng)一異常處理, 才會沒有提示自定義的信息
到此這篇關(guān)于SpringBoot自定義注解驗證枚舉的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot自定義注解驗證枚舉內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springMVC向Controller傳值出現(xiàn)中文亂碼的解決方案
這篇文章主要介紹了springMVC向Controller傳值出現(xiàn)中文亂碼的解決方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
SpringBoot整合mybatis-plus進(jìn)階詳細(xì)教程
本文主要對mybatis-plus的條件構(gòu)造器、AR模式、插件、逆向工程、自定義全局操作、公共字段自動填充等知識點進(jìn)行講解,需要的朋友參考下吧2021-09-09
java的MybatisPlus調(diào)用儲存過程的返回數(shù)據(jù)問題
這篇文章主要介紹了java的MybatisPlus調(diào)用儲存過程的返回數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
Java?中?Class?Path?和?Package的使用詳解
這篇文章主要介紹了Java?中?Class?Path和Package的使用詳解,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-08-08
解決問題:Failed to execute goal org.apache.m
這篇文章主要給大家介紹了關(guān)于解決問題:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources的相關(guān)資料,文中將解決的辦法介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03

