SpringBoot自定義注解驗(yàn)證枚舉的實(shí)現(xiàn)
業(yè)務(wù)場(chǎng)景:數(shù)據(jù)校驗(yàn),需要對(duì)枚舉類型的數(shù)據(jù)傳參,進(jìn)行數(shù)據(jù)校驗(yàn),不能隨便傳參。
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)錯(cuò)誤消息
String message() default "必須為指定值";
// 字符串類型
String[] strValues() default {};
// 整型
int[] intValues() default {};
// 分組
Class<?>[] groups() default {};
// 負(fù)載
Class<? extends Payload>[] payload() default {};
// 忽略null, 為true時(shí),參數(shù)傳null不檢驗(yàn)
boolean ignoreNull() default false;
;
// 指定多個(gè)時(shí)使用
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
EnumValue[] value();
}
}
3、創(chuàng)建自定義檢驗(yàn)器類
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)建請(qǐ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、測(cè)試類
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、啟動(dòng)測(cè)試


因?yàn)樵贠rderReq類中的orderStatus字段添加了注解規(guī)定值在1、2、3、4。如果傳入其他值會(huì)提示異樣, 這里因?yàn)闆](méi)有統(tǒng)一異常處理, 才會(huì)沒(méi)有提示自定義的信息
到此這篇關(guān)于SpringBoot自定義注解驗(yàn)證枚舉的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot自定義注解驗(yàn)證枚舉內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springMVC向Controller傳值出現(xiàn)中文亂碼的解決方案
這篇文章主要介紹了springMVC向Controller傳值出現(xiàn)中文亂碼的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02
SpringBoot整合mybatis-plus進(jìn)階詳細(xì)教程
本文主要對(duì)mybatis-plus的條件構(gòu)造器、AR模式、插件、逆向工程、自定義全局操作、公共字段自動(dòng)填充等知識(shí)點(diǎn)進(jìn)行講解,需要的朋友參考下吧2021-09-09
java的MybatisPlus調(diào)用儲(chǔ)存過(guò)程的返回?cái)?shù)據(jù)問(wèn)題
這篇文章主要介紹了java的MybatisPlus調(diào)用儲(chǔ)存過(guò)程的返回?cái)?shù)據(jù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
Java線程池的幾種實(shí)現(xiàn)方法及常見(jiàn)問(wèn)題解答
下面小編就為大家?guī)?lái)一篇Java線程池的幾種實(shí)現(xiàn)方法及常見(jiàn)問(wèn)題解答。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-05-05
MyBatis實(shí)現(xiàn)萬(wàn)能Map和模糊查詢
本文主要介紹了MyBatis實(shí)現(xiàn)萬(wàn)能Map和模糊查詢,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07
Mybatis插入語(yǔ)句默認(rèn)值不生效的問(wèn)題及解決
這篇文章主要介紹了Mybatis插入語(yǔ)句默認(rèn)值不生效的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
Java?中?Class?Path?和?Package的使用詳解
這篇文章主要介紹了Java?中?Class?Path和Package的使用詳解,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08
解決問(wèn)題:Failed to execute goal org.apache.m
這篇文章主要給大家介紹了關(guān)于解決問(wèn)題:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources的相關(guān)資料,文中將解決的辦法介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03

