SpringBoot自定義注解驗證枚舉的實現(xiàn)
業(yè)務場景:數(shù)據(jù)校驗,需要對枚舉類型的數(shù)據(jù)傳參,進行數(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 {
// 默認錯誤消息
String message() default "必須為指定值";
// 字符串類型
String[] strValues() default {};
// 整型
int[] intValues() default {};
// 分組
Class<?>[] groups() default {};
// 負載
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)一異常處理, 才會沒有提示自定義的信息
到此這篇關于SpringBoot自定義注解驗證枚舉的實現(xiàn)的文章就介紹到這了,更多相關SpringBoot自定義注解驗證枚舉內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Maven dependencyManagement元素標簽的具體使用
在Maven中dependencyManagement的作用其實相當于一個對所依賴jar包進行版本管理的管理器,本文主要介紹了Maven dependencyManagement元素標簽的具體使用,感興趣的可以了解一下2024-03-03
Java實現(xiàn)上傳網(wǎng)絡圖片到七牛云存儲詳解
這篇文章主要為大家詳細介紹了Java如何實現(xiàn)上傳網(wǎng)絡圖片到七牛云存儲,文中的示例代碼講解詳細,具有一定的借鑒價值,感興趣的小伙伴可以跟隨小編一起學習一下2022-12-12
SpringBoot集成Redis實現(xiàn)訂單超時管理的詳細步驟
文章描述了如何使用Redis來處理超時支付訂單,包括引入依賴、配置連接、定義實體類、實現(xiàn)服務和監(jiān)聽器等步驟,文章討論了優(yōu)化方案、注意事項以及Redis的性能和可靠性問題,感興趣的朋友跟隨小編一起看看吧2026-03-03
MybatisPlus的LambdaQueryWrapper用法詳解
LambdaQueryWrapper<Tag>?是 MyBatis-Plus 框架中的一個功能強大的查詢構造器,它用于構建 SQL 查詢條件,具有一定的參考價值,感興趣的可以了解一下2024-10-10

