SpringBoot自定義注解驗(yàn)證枚舉的實(shí)現(xiàn)
業(yè)務(wù)場景:數(shù)據(jù)校驗(yàn),需要對枚舉類型的數(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)建請求類
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、啟動(dòng)測試


因?yàn)樵贠rderReq類中的orderStatus字段添加了注解規(guī)定值在1、2、3、4。如果傳入其他值會(huì)提示異樣, 這里因?yàn)闆]有統(tǒng)一異常處理, 才會(huì)沒有提示自定義的信息
到此這篇關(guān)于SpringBoot自定義注解驗(yàn)證枚舉的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot自定義注解驗(yàn)證枚舉內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Maven dependencyManagement元素標(biāo)簽的具體使用
在Maven中dependencyManagement的作用其實(shí)相當(dāng)于一個(gè)對所依賴jar包進(jìn)行版本管理的管理器,本文主要介紹了Maven dependencyManagement元素標(biāo)簽的具體使用,感興趣的可以了解一下2024-03-03
Java實(shí)現(xiàn)上傳網(wǎng)絡(luò)圖片到七牛云存儲詳解
這篇文章主要為大家詳細(xì)介紹了Java如何實(shí)現(xiàn)上傳網(wǎng)絡(luò)圖片到七牛云存儲,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-12-12
Java實(shí)現(xiàn)List去重的五種方法詳解
這篇文章主要為大家詳細(xì)介紹了Java中List去重的5種方法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)和參考價(jià)值,需要的小伙伴可以了解一下2022-10-10
SpringBoot集成Redis實(shí)現(xiàn)訂單超時(shí)管理的詳細(xì)步驟
文章描述了如何使用Redis來處理超時(shí)支付訂單,包括引入依賴、配置連接、定義實(shí)體類、實(shí)現(xiàn)服務(wù)和監(jiān)聽器等步驟,文章討論了優(yōu)化方案、注意事項(xiàng)以及Redis的性能和可靠性問題,感興趣的朋友跟隨小編一起看看吧2026-03-03
MybatisPlus的LambdaQueryWrapper用法詳解

