Java自定義注解對(duì)枚舉類(lèi)型參數(shù)的校驗(yàn)方法
1.前提準(zhǔn)備條件
java注解了解http://chabaoo.cn/program/287468xs5.htm
1.1 pom.xml文件依賴(lài):
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.8-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.knife4j</groupId> <artifactId>MyKnife4jDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>MyKnife4jDemo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>17</java.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-dependencies</artifactId> <version>4.5.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>8.0.0.Final</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>nexus-maven</id> <name>nexus-maven</name> <url>https://oss.sonatype.org/content/repositories/snapshots/</url> </repository> </repositories> </project>
1.2 枚舉類(lèi):
@Getter @AllArgsConstructor public enum RoleEnum { ADMIN("A", "Administrator"), USER("U", "User"), GUEST("G", "Guest"); private final String code; private final String name; public static RoleEnum fromCode(String code) { for (RoleEnum role : RoleEnum.values()) { if (role.getCode().equals(code)) { return role; } } throw new IllegalArgumentException("Unknown code: " + code); } }
1.3 controller接口:
@RequestMapping("/user") @RestController @Tag(name = "用戶(hù)控制類(lèi)") public class UserController { @PostMapping("/add") @Operation(description = "添加數(shù)據(jù)") public UserDTO validCreate(@RequestBody @Valid UserDTO userDTO) { return userDTO; } }
1.4 實(shí)體參數(shù):
@NoArgsConstructor @AllArgsConstructor @Data @Schema(description = "用戶(hù)新增--DTO") public class UserDTO { @Schema(description = "用戶(hù)名") @NotBlank(message = "用戶(hù)名不能為空") private String userName; @Schema(description = "用戶(hù)編號(hào)") @NotBlank(message = "用戶(hù)編號(hào)不能為空") private String userNo; @Schema(description = "角色編碼") private String roleCode; }
1.5 knife4j的配置
我是結(jié)合Knife4j來(lái)使用的,knife4j的詳細(xì)了解使用如下鏈接:
knife4j的配置如下:
@Configuration @EnableKnife4j public class Knife4jConfig { @Bean public OpenAPI openAPI() { return new OpenAPI() .info(new Info() .title("knife4j-openapi3入門(mén)測(cè)試") .version("1.0") .description("knife4j-openapi3項(xiàng)目的接口文檔")); } @Bean public GroupedOpenApi userAPI() { return GroupedOpenApi.builder().group("用戶(hù)信息管理"). pathsToMatch("/user/**"). build(); } }
2.實(shí)現(xiàn)要求
希望對(duì)參數(shù)UserDTO中的字段roleCode進(jìn)行自動(dòng)校驗(yàn),校驗(yàn)roleCode參數(shù)必須且只能是枚舉類(lèi)中的編碼的其中一個(gè)。通過(guò)注解的方式實(shí)現(xiàn),最大程度上提高參數(shù)的靈活性。
3.實(shí)現(xiàn)步驟
3.1 自定義注解類(lèi):
@Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = EnumCodeValidator.class) public @interface ValidEnumCode { String message() default "must be any of enum {enumClass} codes"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; Class<? extends Enum<?>> enumClass(); }
3.2 使用注解:
在字段roleCode上添加自定義注解:
@NoArgsConstructor @AllArgsConstructor @Data @Schema(description = "用戶(hù)新增--DTO") public class UserDTO { @Schema(description = "用戶(hù)名") @NotBlank(message = "用戶(hù)名不能為空", groups = {Create.class}) private String userName; @Schema(description = "用戶(hù)編號(hào)") @NotBlank(message = "用戶(hù)編號(hào)不能為空", groups = {Update.class}) private String userNo; @Schema(description = "角色編碼") @ValidEnumCode(enumClass = RoleEnum.class,message = "Role code must be any of {codes} from {enumClass}") private String roleCode; }
3.3 添加注解校驗(yàn)類(lèi):
public class EnumCodeValidator implements ConstraintValidator<ValidEnumCode, CharSequence> { private List<String> acceptedCodes; private String messageTemplate; private String enumClassName; @Override public void initialize(ValidEnumCode constraintAnnotation) { Class<? extends Enum<?>> enumClass = constraintAnnotation.enumClass(); acceptedCodes = Stream.of(enumClass.getEnumConstants()) .map(this::getEnumCode) .collect(Collectors.toList()); messageTemplate = constraintAnnotation.message(); enumClassName = enumClass.getSimpleName(); } private String getEnumCode(Enum<?> enumConstant) { try { Method getCodeMethod = enumConstant.getClass().getMethod("getCode"); return (String) getCodeMethod.invoke(enumConstant); } catch (Exception e) { throw new RuntimeException("Failed to get enum code", e); } } @Override public boolean isValid(CharSequence value, ConstraintValidatorContext context) { if (value == null) { return true; } if (!acceptedCodes.contains(value.toString())) { String message = messageTemplate.replace("{enumClass}", enumClassName) .replace("{codes}", String.join(", ", acceptedCodes)); context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(message) .addConstraintViolation(); return false; } return true; } }
3.4 啟動(dòng)測(cè)試
若我傳的參數(shù)如下則不通過(guò):
后端控制臺(tái)也會(huì)打印出如下提示:
若我按要求傳參數(shù),就能得到正確的結(jié)果:
4.擴(kuò)展
根據(jù)我在pom中引入的參數(shù)校驗(yàn)依賴(lài):hibernate-validator,
找到擴(kuò)展依賴(lài)中的如下兩個(gè)依賴(lài),查看其他的可用的參數(shù)校驗(yàn)注解:
打開(kāi)之后,根據(jù)下述提示找到可使用的注解,自己可測(cè)試使用哦
嗯,完結(jié)了,希望大家能多多對(duì)我提出點(diǎn)建議。
到此這篇關(guān)于Java自定義注解對(duì)枚舉類(lèi)型參數(shù)的校驗(yàn)的文章就介紹到這了,更多相關(guān)java枚舉類(lèi)型參數(shù)校驗(yàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實(shí)現(xiàn)操作系統(tǒng)中的最佳置換Optimal算法
這篇文章主要介紹了java實(shí)現(xiàn)操作系統(tǒng)中的最佳置換Optimal算法 ,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02springboot下添加日志模塊和設(shè)置日志文件輸出的方法
日志的使用將通過(guò)SLF4J來(lái)使用,SLF4J是一個(gè)為Java應(yīng)用提供簡(jiǎn)單日志記錄的接口,在Spring框架中,SLF4J常常用于處理框架本身以及應(yīng)用程序的日志記錄,本文給大家介紹springboot下添加日志模塊和設(shè)置日志文件輸出的相關(guān)知識(shí),感興趣的朋友一起看看吧2023-12-12使用java為pdf添加書(shū)簽的方法(pdf書(shū)簽制作)
下載一些pdf格式的電子書(shū)沒(méi)有書(shū)簽,用JAVA寫(xiě)了一個(gè)小工具,將特定格式的文本解析成為書(shū)簽,然后保存到pdf格式中2014-02-02java實(shí)現(xiàn)超市商品庫(kù)存管理平臺(tái)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)超市商品庫(kù)存管理平臺(tái),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10把spring boot項(xiàng)目發(fā)布tomcat容器(包含發(fā)布到tomcat6的方法)
這篇文章主要介紹了把spring boot項(xiàng)目發(fā)布tomcat容器(包含發(fā)布到tomcat6的方法),然后在文章給大家提到了如何將Spring Boot項(xiàng)目打包部署到外部Tomcat,需要的朋友參考下吧2017-11-11