SpringDoc枚举字段处理与SpringBoot接收枚举参数处理

2023-11-22 11:36

本文主要是介绍SpringDoc枚举字段处理与SpringBoot接收枚举参数处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本期内容

  1. 添加SpringDoc配置展示枚举字段,在文档页面中显示枚举值和对应的描述
  2. 添加SpringMVC配置使项目可以接收枚举值,根据枚举值找到对应的枚举

默认内容

先不做任何处理看一下直接使用枚举当做入参是什么效果。

  1. 定义一个枚举
package com.example.enums;import lombok.AllArgsConstructor;
import lombok.Getter;/*** 来源枚举** @author vains*/
@Getter
@AllArgsConstructor
public enum SourceEnum {/*** 1-web网站*/WEB(1, "web网站"),/*** 2-APP应用*/APP(2, "APP应用");/*** 来源代码*/private final Integer value;/*** 来源名称*/private final String source;}
  1. 定义一个入参类
package com.example.model;import com.example.enums.SourceEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;/*** 枚举属性类** @author vains*/
@Data
@Schema(title = "包含枚举属性的类")
public class EnumModel {@Schema(title = "名字")private String name;@Schema(title = "来源")private SourceEnum source;}
  1. 定义一个接口,测试枚举入参的效果
package com.example.controller;import com.example.enums.SourceEnum;
import com.example.model.EnumModel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** 枚举接口** @author vains*/
@RestController
@RequestMapping("/enum")
@Tag(name = "枚举入参接口", description = "提供以枚举作为入参的接口,展示SpringDoc自定义配置效果")
public class EnumController {@GetMapping("/test01/{source}")@Operation(summary = "url参数枚举", description = "将枚举当做url参数")public SourceEnum test01(@PathVariable SourceEnum source) {return source;}@GetMapping("/test02")@Operation(summary = "查询参数枚举", description = "将枚举当做查询参数")public SourceEnum test02(SourceEnum source) {return source;}@PostMapping(value = "/test03")@Operation(summary = "参数类包含枚举", description = "将枚举当做参数类的属性")public EnumModel test03(@RequestBody EnumModel model) {return model;}}
  1. 启动项目,查看接口文档显示效果

    单个枚举效果
    默认情况下接口显示效果
    作为参数属性显示效果
    枚举作为参数显示效果

文档中默认显示枚举可接收的值是定义的枚举名字(APP,WEB),但是在实际开发中前端会传入枚举对应的值/代码(1,2),根据代码映射到对应的枚举。

解决方案

单个处理方案

枚举入参

详细内容见文档

使用@Parameter注解(方法上/参数前)或者@Parameters注解来指定枚举参数可接受的值。如下所示

例1

@GetMapping("/test01/{source}")
@Parameter(name = "source", schema = @Schema(description = "来源枚举", type = "int32", allowableValues = {"1", "2"}))
@Operation(summary = "url参数枚举", description = "将枚举当做url参数")
public SourceEnum test01(@PathVariable SourceEnum source) {return source;
}

例2

@GetMapping("/test01/{source}")
@Operation(summary = "url参数枚举", description = "将枚举当做url参数")
public SourceEnum test01(@PathVariable@Parameter(name = "source", schema =@Schema(description = "来源枚举", type = "int32", allowableValues = {"1", "2"}))SourceEnum source) {return source;
}

单独枚举入参显示效果

注解标注效果

枚举作为参数类属性

单独处理没有好的办法,像上边添加allowableValues属性只会在原有列表上添加,如下

添加allowableValues属性效果

全局统一处理方案

准备工作

  1. 定义一个统一枚举接口
package com.example.enums;import com.fasterxml.jackson.annotation.JsonValue;import java.io.Serializable;
import java.util.Arrays;
import java.util.Objects;/*** 通用枚举接口** @param <V> 枚举值的类型* @param <E> 子枚举类型* @author vains*/
public interface BasicEnum<V extends Serializable, E extends Enum<E>> {@JsonValueV getValue();/*** 根据子枚举和子枚举对应的入参值找到对应的枚举类型** @param value 子枚举中对应的值* @param clazz 子枚举类型* @param <B>   {@link BasicEnum} 的子类类型* @param <V>   子枚举值的类型* @param <E>   子枚举的类型* @return 返回 {@link BasicEnum} 对应的子类实例*/static <B extends BasicEnum<V, E>, V extends Serializable, E extends Enum<E>> B fromValue(V value, Class<B> clazz) {return Arrays.stream(clazz.getEnumConstants()).filter(e -> Objects.equals(e.getValue(), value)).findFirst().orElse(null);}}

我这里为了通用性将枚举值的类型也设置为泛型类型了,如果不需要可以设置为具体的类型,比如StringInteger等,如果像我这样处理起来会稍微麻烦一些;另外我这里只提供了一个getValue的抽象方法,你也可以再提供一个getNamegetDescription等获取枚举描述字段值的抽象方法。

  1. 让项目中的枚举实现BasicEnum接口并重写getValue方法,如下
package com.example.enums;import lombok.AllArgsConstructor;
import lombok.Getter;/*** 来源枚举** @author vains*/
@Getter
@AllArgsConstructor
public enum SourceEnum implements BasicEnum<Integer, SourceEnum> {/*** 1-web网站*/WEB(1, "web网站"),/*** 2-APP应用*/APP(2, "APP应用");/*** 来源代码*/private final Integer value;/*** 来源名称*/private final String source;}
  1. 定义一个基础自定义接口,提供一些对枚举的操作方法
package com.example.config.basic;import io.swagger.v3.core.util.PrimitiveType;
import io.swagger.v3.oas.models.media.ObjectSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ReflectionUtils;import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;/*** 基础自定义接口** @author vains*/
public interface BasicEnumCustomizer {/*** 获取枚举的所有值** @param enumClazz 枚举的class* @return 枚举的所有值*/default List<Object> getValues(Class<?> enumClazz) {return Arrays.stream(enumClazz.getEnumConstants()).filter(Objects::nonNull).map(item -> {// 收集valuesMethod getValue = ReflectionUtils.findMethod(item.getClass(), "getValue");if (getValue != null) {ReflectionUtils.makeAccessible(getValue);return ReflectionUtils.invokeMethod(getValue, item);}return null;}).filter(Objects::nonNull).toList();}/*** 获取值和描述对应的描述信息,值和描述信息以“:”隔开** @param enumClazz 枚举class* @return 描述信息*/default String getDescription(Class<?> enumClazz) {List<Field> fieldList = Arrays.stream(enumClazz.getDeclaredFields()).filter(f -> !Modifier.isStatic(f.getModifiers()))// 排序.sorted(Comparator.comparing(Field::getName).reversed()).toList();fieldList.forEach(ReflectionUtils::makeAccessible);return Arrays.stream(enumClazz.getEnumConstants()).filter(Objects::nonNull).map(item -> fieldList.stream().map(field -> ReflectionUtils.getField(field, item)).map(String::valueOf).collect(Collectors.joining(" : "))).collect(Collectors.joining("; "));}/*** 根据枚举值的类型获取对应的 {@link Schema} 类*  这么做是因为当SpringDoc获取不到属性的具体类型时会自动生成一个string类型的 {@link Schema} ,*  所以需要根据枚举值的类型获取不同的实例,例如 {@link io.swagger.v3.oas.models.media.IntegerSchema}、*  {@link io.swagger.v3.oas.models.media.StringSchema}** @param type         枚举值的类型* @param sourceSchema 从属性中加载的 {@link Schema} 类* @return 获取枚举值类型对应的 {@link Schema} 类*/@SuppressWarnings({"unchecked"})default Schema<Object> getSchemaByType(Type type, Schema<?> sourceSchema) {Schema<Object> schema;PrimitiveType item = PrimitiveType.fromType(type);if (item == null) {schema = new ObjectSchema();} else {schema = item.createProperty();}// 获取schema的type和formatString schemaType = schema.getType();String format = schema.getFormat();// 复制原schema的其它属性BeanUtils.copyProperties(sourceSchema, schema);// 使用根据枚举值类型获取到的schemareturn schema.type(schemaType).format(format);}}

全局自定义内容都是基于org.springdoc.core.customizers包下的一些Customizer接口,SpringDoc在扫描接口信息时会调用这些接口以实现加载使用者的自定义内容,所以这里提供一个基础的Customizer接口。

实现枚举参数自定义

定义一个ApiEnumParameterCustomizer类并实现ParameterCustomizer接口,实现对枚举入参的自定义,同时实现BasicEnumCustomizer接口使用工具方法。

package com.example.config.customizer;import com.example.config.basic.BasicEnumCustomizer;
import com.example.enums.BasicEnum;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.springdoc.core.customizers.ParameterCustomizer;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;/*** 枚举参数自定义配置** @author vains*/
@Component
public class ApiEnumParameterCustomizer implements ParameterCustomizer, BasicEnumCustomizer {@Overridepublic Parameter customize(Parameter parameterModel, MethodParameter methodParameter) {Class<?> parameterType = methodParameter.getParameterType();// 枚举处理if (BasicEnum.class.isAssignableFrom(parameterType)) {parameterModel.setDescription(getDescription(parameterType));Schema<Object> schema = new Schema<>();schema.setEnum(getValues(parameterType));parameterModel.setSchema(schema);}return parameterModel;}
}

实现枚举属性的自定义

定义一个ApiEnumPropertyCustomizer类并实现PropertyCustomizer接口,实现对枚举属性的自定义,同时实现BasicEnumCustomizer接口使用工具方法。

package com.example.config.customizer;import com.example.config.basic.BasicEnumCustomizer;
import com.example.enums.BasicEnum;
import com.fasterxml.jackson.databind.type.SimpleType;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.oas.models.media.Schema;
import org.springdoc.core.customizers.PropertyCustomizer;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;/*** 枚举属性自定义配置** @author vains*/
@Component
public class ApiEnumPropertyCustomizer implements PropertyCustomizer, BasicEnumCustomizer {@Overridepublic Schema<?> customize(Schema property, AnnotatedType type) {// 检查实例并转换if (type.getType() instanceof SimpleType fieldType) {// 获取字段classClass<?> fieldClazz = fieldType.getRawClass();// 是否是枚举if (BasicEnum.class.isAssignableFrom(fieldClazz)) {// 获取父接口if (fieldClazz.getGenericInterfaces()[0] instanceof ParameterizedType parameterizedType) {// 通过父接口获取泛型中枚举值的class类型Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0];Schema<Object> schema = getSchemaByType(actualTypeArgument, property);// 重新设置字段的注释和默认值schema.setEnum(this.getValues(fieldClazz));// 获取字段注释String description = this.getDescription(fieldClazz);// 重置字段注释和标题为从枚举中提取的if (ObjectUtils.isEmpty(property.getTitle())) {schema.setTitle(description);} else {schema.setTitle(property.getTitle() + " (" + description + ")");}if (ObjectUtils.isEmpty(property.getDescription())) {schema.setDescription(description);} else {schema.setDescription(property.getDescription() + " (" + description + ")");}return schema;}}}return property;}}

如果读者不喜欢这样的效果可以自行修改枚举值、描述信息的显示效果

重启项目查看效果

接口1
/test01
接口2
/test02
接口3
/test03

SpringBoot接收枚举入参处理

不知道大家有没有注意到BasicEnum接口中的抽象方法getValue上有一个@JsonValue注解,这个注解会在进行Json序列化时会将该方法返回的值当做当前枚举的值,例如:1/2,如果不加该注解则序列化时会直接变为枚举的名字,例如: APP/WEB。

如果Restful接口入参中有@RequestBody注解则在——统一枚举的getValue方法上有@JsonValue注解的基础上,无需做任何处理,对于Json入参可以这样处理,但是对于POST表单参数或GET查询参数需要添加单独的处理。

定义一个EnumConverterFactory

根据枚举的class类型获取对应的converter,并在converter中直接将枚举值转为对应的枚举
,具体逻辑情况代码中的注释

package com.example.config.converter;import com.example.enums.BasicEnum;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.NonNull;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.Function;/*** 处理除 {@link org.springframework.web.bind.annotation.RequestBody } 注解标注之外是枚举的入参** @param <V> 枚举值的类型* @param <E> 枚举的类型* @author vains*/
@Component
public class EnumConverterFactory<V extends Serializable, E extends Enum<E>> implements ConverterFactory<String, BasicEnum<V, E>> {@NonNull@Override@SuppressWarnings("unchecked")public <T extends BasicEnum<V, E>> Converter<String, T> getConverter(Class<T> targetType) {// 获取父接口Type baseInterface = targetType.getGenericInterfaces()[0];if (baseInterface instanceof ParameterizedType parameterizedType&& parameterizedType.getActualTypeArguments().length == 2) {// 获取具体的枚举类型Type targetActualTypeArgument = parameterizedType.getActualTypeArguments()[1];Class<?> targetAawArgument = TypeFactory.defaultInstance().constructType(targetActualTypeArgument).getRawClass();// 判断是否实现自通用枚举if (BasicEnum.class.isAssignableFrom(targetAawArgument)) {// 获取父接口的泛型类型Type valueArgument = parameterizedType.getActualTypeArguments()[0];// 获取值的classClass<V> valueRaw = (Class<V>) TypeFactory.defaultInstance().constructType(valueArgument).getRawClass();String valueOfMethod = "valueOf";// 转换入参的类型Method valueOf = ReflectionUtils.findMethod(valueRaw, valueOfMethod, String.class);if (valueOf != null) {ReflectionUtils.makeAccessible(valueOf);}// 将String类型的值转为枚举值对应的类型Function<String, V> castValue =// 获取不到转换方法时直接返回nullsource -> {if (valueRaw.isInstance(source)) {// String类型直接强转return valueRaw.cast(source);}// 其它包装类型使用valueOf转换return valueOf == null ? null: (V) ReflectionUtils.invokeMethod(valueOf, valueRaw, source);};return source -> BasicEnum.fromValue(castValue.apply(source), targetType);}}return source -> null;}}

定义一个WebmvcConfig配置类,将EnumConverterFactory注册到添加到mvc配置中

package com.example.config;import com.example.config.converter.EnumConverterFactory;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** 添加自定义枚举转换配置** @author vains*/
@AllArgsConstructor
@Configuration(proxyBeanMethods = false)
public class WebmvcConfig implements WebMvcConfigurer {private final EnumConverterFactory<?, ?> enumConverterFactory;@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addConverterFactory(enumConverterFactory);}
}

重启项目并打开在线文档进行测试

枚举入参示例

Gitee地址、Github地址

这篇关于SpringDoc枚举字段处理与SpringBoot接收枚举参数处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/409860

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

无人叉车3d激光slam多房间建图定位异常处理方案-墙体画线地图切分方案

墙体画线地图切分方案 针对问题:墙体两侧特征混淆误匹配,导致建图和定位偏差,表现为过门跳变、外月台走歪等 ·解决思路:预期的根治方案IGICP需要较长时间完成上线,先使用切分地图的工程化方案,即墙体两侧切分为不同地图,在某一侧只使用该侧地图进行定位 方案思路 切分原理:切分地图基于关键帧位置,而非点云。 理论基础:光照是直线的,一帧点云必定只能照射到墙的一侧,无法同时照到两侧实践考虑:关

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

Andrej Karpathy最新采访:认知核心模型10亿参数就够了,AI会打破教育不公的僵局

夕小瑶科技说 原创  作者 | 海野 AI圈子的红人,AI大神Andrej Karpathy,曾是OpenAI联合创始人之一,特斯拉AI总监。上一次的动态是官宣创办一家名为 Eureka Labs 的人工智能+教育公司 ,宣布将长期致力于AI原生教育。 近日,Andrej Karpathy接受了No Priors(投资博客)的采访,与硅谷知名投资人 Sara Guo 和 Elad G